Best case time complexity for selection sort

user3740951 picture user3740951 · Apr 8, 2017 · Viewed 16.5k times · Source

Why is the best case time complexity for selection sort O(n^2) when it is O(n) for insertion sort and bubble sort? Their average times are same. I don't understand why the best case times are different. Would appreciate some help.

Answer

gartenkralle picture gartenkralle · Apr 8, 2017

For selection sort you have to search the minimum and put it on the first place in the first iteration. In the second iteration you have to search the minimum in the non-sorted part of the array and put it to the second place and so on...

You only know which element is the minimum after iterate till the end of the non-sorted part. Even if the array is sorted(!) you have to iterate till the end. Then you know for sure you found the minimum to put it on the right place (at the end of the already sorted part)

So first iteration takes n steps to find the minimum. The second iteration takes n-1 steps to find the minimum in the non-sorted part ... The last iteration takes 1 step to find the minimum in the non-sorted part.

After these steps you have an sorted array (even it was sorted before). Selection sort does not check if the array is already sorted by an linear-time algorithm. Selection sort repeatedly searches the minimum. That's the way how selection sort works.

When you repeatedly search the minimum it takes n+(n-1)+...+1 so you get (n(n+1))/2 = (n²+n)/2 which is in O(n²)