Here are the algorithms for Insertion Sort. The first one uses shifting mechanism for placing the value in the left sorted part. The second one swaps the consecutive values until the left portion becomes sorted.
By Shifting
function insertionSort(array A) for i from 1 to length[A]-1 do value := A[i] j := i-1 while j >= 0 and A[j] > value do A[j+1] := A[j] j := j-1 done A[j+1] = value doneBy Swapping
function insertionSort(array A) for (i =0; i<N; i++) for(int j=i; j>0; j--) if(less(A[j], A[j-1])) exch(A, j, j-1) else break; done done
Wikipedia says this about the run time analysis of Insertion Sort:
Worst case performance: O(n^2) comparisons, swaps Best case performance: O(n) comparisons, O(1) swaps Average case performance: O(n^2) comparisons, swaps which fits with the algorithm 2. But in case of algorithm 1, the analysis becomes:
Worst case performance: O(n^2) comparisons, O(n) swaps Best case performance: O(n) comparisons, O(1) (no) swaps Average case performance: O(n^2) comparisons, O(n) swaps Please clarify the meaning of shifting and swapping.
O(n)best-case performance which is really the only thing insertion sort has going for it.std::upper_boundandstd::rotateusing the standard library.O(n)because each element is only compared to the one before it. If each element were compared withlog kelements to determine the insertion location, the resultant performance would beO(n log n). See Knuth, Vol. 3, p.80. (Normal) insertion sort doesn't have a binary search.