Insertion sort

Insertion sort is a simple sorting algorithm that is asymptotically equivalent to bubble sort, but is much faster in practice, because the number of swaps is at most linear. Its complexity is $$O(n^2)$$, in-place, and is stable.

Insertion sort is preferable when the number of items is small - the constant is small enough that the benefit due to excellent locality and noticably better when the entire list fits in the lower levels of caching. Insertion sort is also quick when the list is nearly sorted. Introsort exploits these properties by using this sort after quicksort or heap sort have made a few passes on the list.

Insertion sort in an array with gaps can achieve the theoretical lower bound of $$O(n \log n)$$ of sorting with high probability. (Bender, Farach-Colton, Mosteiro, 2004)

Algorithm

 * 1) Iterate through the array, starting from the second element:
 * 2) Note the element at this index.
 * 3) Walk back through the previous elements until you find a smaller element (or the beginning of the array), moving each element up by one.
 * 4) Insert the noted element at this point.

Pseudocode
for i from 1 to N  key = a[i] j = i - 1 while j >= 0 and a[j] > key a[j+1] = a[j] j = j - 1 a[j+1] = key next i
 * a is an array of size N