Insertion sort is a type of sort that simply sort an array.
It is less efficient than quick sort, merge sort. However, it is simply implemented and it works for small data sets.
In worst and average case its time complexity is O(n^2) (square of n), in best case, its time complexity is O(n).
It has several advantages:
- In-place : only needs O(1) additional memory,
- Simple implementation,
- Efficient for small data sets.
How does it work?
Insertion sort iterates and growing a sorted list. In each iteration, it takes an element from list and finds the exact location of it in the list. After that it places in the correct place, iteration goes on until list is fully sorted. In each iteration, an element (x) places to the right place and list becomes sorted like example below.
In picture below, you can see the insertion sort example.
Insertion Sort Example
For better understanding, go to this animation page.
Insertion Sort ( X[ ] , n) for j <- 2 to n key <- X [ j ] i <- j - 1 while i > 0 and X [ i ] > key X [ i + 1 ] <- X [ i ] i < - i -1 X [ i + 1 ] = key
Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2001), “2.1: Insertion sort”, Introduction to Algorithms (second ed.), MIT Press and McGraw-Hill, pp. 15–21.
Figures from: http://en.wikipedia.org
For more algorithms, go to Algorithms Section.