Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best case time complexity for selection sort

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.

like image 754
user3740951 Avatar asked Apr 08 '17 17:04

user3740951


People also ask

What is the best case scenario for selection sort?

For selection sort, the best case is items already in order. However, that doesn't really improve the running time appreciably. Selection sort has no early-out condition; you have to check every item regardless of whether the list is already in order.

What is the best and worst complexity of selection sort?

Since the swapping only takes a constant amount of time i.e. O ( 1 ) O(1) O(1)the best time complexity of selection sort comes out to be O ( N 2 ) O(N^2) O(N2). The worst case is when the array is completely unsorted or sorted in descending order.


1 Answers

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²)

like image 125
gartenkralle Avatar answered Oct 07 '22 10:10

gartenkralle