Insertion Sort
What is an insertion sort?
A simple sorting algorithm which moves elements one at a time into the correct position, moving higher ranked elements up as necessary. It repeats until no input elements remain.
Which Big O?
- O ( 1 ) = constant time (process time same regardless of array size)
- O ( log n ) = log arithmetic (needs to be sorted)
- O ( n ) = linear (i.e. twitter followers, increasing size takes longer)
- O ( n log n ) = semi linear
- O (n2) = quadratic (for loops)
- O ( nk ) = polynomial
- O ( Kn ) = Exponential time
- O ( n! ) = factorial time
sudo code for algorithm
for i = 1 to n - 1 //loops over the index of the entry to be inserted
j = i
while j > 0 and A[j] < A[j - 1] // while loop performs the insertion
swap(A[j], A[j - 1}) //swaps the element before as long as it is less
j = j - 1
The Code
How it works...
When to use it
Good
- simplicity and efficiency
- takes advantage of presorting
- efficient for quite small data sets
- more efficient in practice than most other simple quadratic algorithm such as selection sort or bubble sort
Bad
- less efficient on large lists than more advanced algorithms such as quick sort, heap sort or merge sort
Resources
Good
- http://en.wikipedia.org/wiki/Insertion_sort
- http://www.sorting-algorithms.com/insertion-sort
- http://rosettacode.org/wiki/Sorting_algorithms/Insertion_sort
- https://www.youtube.com/watch?v=i-SKeOcBwko
- http://bateru.com/news/2011/03/code-of-the-day-javascript-insertion-sort/
Algorithms
By vic_lee
Algorithms
- 310