If integers are nearly or almost sorted , then insertion sort is the best.
If we race all the four algorithms, then clearly insertion sort is the winner . Insertion sort provides a O(n2) worst case algorithm that adapts to O(n) time when the data is nearly or almost sorted.
- Bubble sort is fast and comes second bcoz insertion sort has lower overhead and even if completely sorted , bubble sort again traverses all the elements to know that no swaps are needed which has high overhead.
-
- Shell sort is fast and comes third because it is based on insertion sort.
- Selection sort is not good for this case and is very slow .
- Merge sort, heap sort, and quick sort do not even adapt to nearly sorted data.
- Time complexity ===>
Insertion sort --> O(n) and it will take some 1 pass
Bubble sort --> O(n) and it will take some 2 pass or can be more (1 for actual swapping and last pass for again checking that this time no pass occurs which is overhead) .
Shell sort ---> O(nlogn)
Selection sort --> O(n2 )...