Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why insertion sort is best algorithm for sorted or nearly sorted array?

So i guess its because it just compares A[k] and A[k-1], and does the implementation in one sweep but its still not clear. Can someone explain better. Thanks

like image 773
Katrina Avatar asked Jan 01 '26 03:01

Katrina


2 Answers

This link shows a graphical representation of sorting algorithm with different types of data set. As you can see, when the data is sorted the algorithm complexity is reduced to N. Which is equivalent to the number of elements as inputs.

The link provided gives a clear picture of how its more efficient.

like image 191
Kishore Bandi Avatar answered Jan 05 '26 05:01

Kishore Bandi


You answered your own question: For a nearly sorted array, insertion sort will only need a handful of O(n) passes to complete. Contrast that to a divide and conquer sorting algorithm like merge sort, which takes O(n*lgn). For any non trivial value of n, a divide and conquer algorithm will need many O(n) passes, even if the array be almost completely sorted, whereas insertion sort might only require a few.

like image 22
Tim Biegeleisen Avatar answered Jan 05 '26 07:01

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!