Insertion sort
From Wikipedia, the free encyclopedia
(Redirected from Insertion Sort)
Example of insertion sort sorting a list of random numbers. | |
Class | Sorting algorithm |
---|---|
Data structure | Array |
Worst case performance | О(n2) |
Best case performance | O(n) |
Average case performance | О(n2) |
Worst case space complexity | О(n) total, O(1) auxiliary |
- 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
Contents[hide] |
[edit] 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
Walang komento:
Mag-post ng isang Komento