Insertion sort
From Wikipedia, the free encyclopedia
(Redirected from
Insertion Sort)
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: the time 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
When humans manually sort something (for example, a deck of playing cards), most use a method that is similar to insertion sort.
[1]
[edit] Algorithm
An example of insertion sort. Check each element and put it in the right place in the sorted list.
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