Insertion sort is a simple sorting algorithm: a comparison sort in which the sorted array (or list) is built one entry at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:
- Simple implementation
- Efficient for (quite) small data sets
- Adaptive, i.e. efficient for data sets that are already substantially sorted: thet ime complexity is O(n + d), where d is the number of inversions
- More efficient in practice than most other simple quadratic, i.e. O(n2) algorithms such as selection sort or bubble sort; the best case (nearly sorted input) is O(n)
- Stable, i.e. does not change the relative order of elements with equal keys
- In-place, i.e. only requires a constant amount O(1) of additional memory space
- Online, i.e. can sort a list as it receives it
Most humans when sorting—ordering a deck of cards, for example—use a method that is similar to insertion sort.
Contents
- 1 Algorithm
- 2 Best, worst, and average cases
- 3 Comparisons to other sorting algorithms
- 4 Variants
- 5 References
- 6 External links
Algorithm
Every repetition of insertion sort removes an element from the input data, inserting it into the correct position in the already-sorted list, until no input elements remain. The choice of which element to remove from the input is arbitrary, and can be made using almost any choice algorithm.
Sorting is typically done in-place. The resulting array after k iterations has the property where the first k + 1 entries are sorted. In each iteration the first remaining entry of the input is removed, inserted into the result at the correct position, thus extending the result:
becomes
with each element greater than x copied to the right as it is compared against x.
The most common variant of insertion sort, which operates on arrays, can be described as follows:
Pseudocode of the complete algorithm follows, where the arrays are zero-based and the for-loop includes both the top and bottom limits.
insertionSort(array A) { This procedure sorts in ascending order. } begin for i := 1 to length[A]-1 do begin value := A[i]; j := i - 1; done := false; repeat { To sort in descending order simply reverse the operator i.e. A[j] < value } if A[j] > value then begin A[j + 1] := A[j]; j := j - 1; if j < 0 then done := true; end else done := true; until done; A[j + 1] := value; end; end;
Below is the pseudocode for insertion sort for a zero-based array (as in C):