Question
Download Solution PDFWhich of the following sorting methods will be the best, if the number of swappings done, is the only measure of efficiency?
Answer (Detailed Solution Below)
Detailed Solution
Download Solution PDFSelection sort is best if efficiency is in terms of swaps. No of the swaps in selection sort is of O(n)
To sort elements in increasing order, selection sort always picks the maximum/minimum element from the remaining unsorted array and swaps it with the last/first element respectively (according to implementation) in the remaining array
Pseudo code of selection sort.
for(i=0;i<n-1;i++)
{
min_idx=i;
for(j=i+i; j<n;><="" p="" style="box-sizing: border-box;">
{
f(a[j] < a[min_idx])
min_idx=j;
}
swap(a[i],a[min_idx]); / only 1 swap each iteration for a total of n-1 iterations
}
Here, the 9th line in pseudo-code there are in a single for loop and loop will run for the n – 1 time
swap condition in code will execute only n – 1 time.
Number of swaps = θ(n) = O(n).
Last updated on May 28, 2025
-> UPSC ESE admit card 2025 for the prelims exam has been released.
-> The UPSC IES Prelims 2025 will be held on 8th June 2025.
-> The selection process includes a Prelims and a Mains Examination, followed by a Personality Test/Interview.
-> Candidates should attempt the UPSC IES mock tests to increase their efficiency. The UPSC IES previous year papers can be downloaded here.