892 views
0 0 votes
For flag based approach in Bubble sort we can check first by a flag if the list is sorted or not in O(n), and if it is sorted, then no need to sort and the operation ends in Best case = O(n).

Why isn't the same concept applicable to selection sort? Why it never comes down from O(n$^2$)?

1 Answer

Best answer
3 3 votes

Because u can't implement it
The bubble sort early termination is based on the fact that, when in one pass there are no swaps, it means the array is now sorted, so we can stop
But, you can't implement the same idea in selection sort
The idea of selection sort is repeatedly "select" smallest element from the unsorted part and swap it with the 1st element of unsorted part,

suppose u try to implement the early termination idea here, like the right, it won't work


The inner for loop is trying to find element smaller than the 1st ele of unsorted part and swap them
Now ,The idea was if i can't find a number smaller than than the 1st ele of unsorted part(ie flag stays 0), then stop,
Yes this will certainly work for sorted input
but will fail for inputs like
1 3 4 2 7
cuz here for i=0 itn,
minimum=1,
now it's minimum so the if condn won't execute hence flag=0
so break, code stops after 1 itn, but array is unsorted
So, the early termination idea of bubble sort won't work here, hence complexity of selection sort stays $O(n^2)$ for all cases

 

edited by
Position:
Show:

Related questions

12 12 votes
1 answers 1 answer
6.5k
6.5k views
Samujjal Das asked Jan 2, 2017
6,545 views
A cache aware sorting algorithm sorts an array of size 2k with each key of size 4 Bytes. The size of the cache memory is 128 Bytes and algorithm is the combination of mer...
9 9 votes
2 answers 2 answers
23.4k
23.4k views
0 0 votes
1 1 answer
884
884 views
Ciado asked Apr 27, 2017
884 views
We have for Counting Sort, O(n+k), for a simple uniform hashing, search operation of O(1+alpha) etc. What is the meaning when we say n + k? Is it that counting sort will ...
4 4 votes
1 1 answer
2.4k
2.4k views
go_editor asked May 22, 2016
2,403 views
You are given two sorting algorithms A and B that work in time $O(n \log n)$ and $O(n^2)$, respectively. Consider the following statements:Algorithm $A$ will sort any arr...