Like Bubble Sort, Insertion Sort is a simple sorting algorithm.
Insertion Sort works by iterating up the current array, placing the current element into the correct place in the new sorted array.
First, take the first element of the unsorted array out of the array and put it into an empty new array.
Take the next element out of the unsorted array and place it into the new array. If it is smaller than the first element in the new array, swap them. If not, leave it at the end.
Take the next element out of the array and put it at the end of the new array. If it is larger than the previous end element, leave it. If not, iterate through the array until you find its correct position and insert it there.
Continue this process until your original array is empty and you have a new completely sorted array.
While more efficent than Bubble Sort, Insertion Sort still has the same average and worse case time complexity of O(n2). Like Bubble Sort, it is very inefficient for large data sets, but rather efficient for small data sets or data sets already mostly sorted (the best case time complexity is O(n)).
functioninsertionSort(array){varsortedArray=[];for(vari=0;i<array.length;i++){sortedArray.push(array[i]);varlen=sortedArray.length;if((len>1)&&(sortedArray[len-1]<sortedArray[len-2])){for(varj=0;j<len;j++){if((len===2)&&(sortedArray[j]>sortedArray[len-1])){varfirst=sortedArray[j];varsecond=sortedArray[len-1];sortedArray[j]=second;sortedArray[len-1]=first;}elseif((sortedArray[j]<=sortedArray[len-1])&&(sortedArray[len-1]<=sortedArray[j+1])){//Insert the new element where it belongs.sortedArray.splice(j+1,0,sortedArray[len-1]);// Delete it from the end of the array.sortedArray.splice(sortedArray.length-1,1);}}}}returnsortedArray;}insertionSort([4,1,2,6,3,5]);//=> [1, 2, 3, 4, 5, 6]
This is the second post in a series of posts on various sorting algorithms in computer science. See the entire series here.