ISRO Scientist/Engineer CSE 2018Algorithms › Sorting
ISRO Scientist/Engineer CSE 2018 PYQ: Of the following sorting algorithms, which has a running time that is least dependent on the initial…
Of the following sorting algorithms, which has a running time that is least dependent on the initial ordering of the input?
- AMege Sort
- BInsertion Sort
- CSelection SortCorrect answer
- DQuick Sort
Answer
(C) Selection Sort
Approach
The key phrase is 'least dependent on the initial ordering of the input', not 'least worst-case complexity' or 'fastest'. Selection sort performs exactly n(n-1)/2 comparisons in every case: best, average, and worst. Its data movement (swaps) can vary from 0 to n-1 depending on the input, but this is O(n), which is asymptotically negligible compared with the $O(n^2)$ comparisons. Thus its total running time is almost completely independent of the initial ordering. Merge sort is O(n log n) in all cases, but its actual running time is not strictly input-independent. The number of comparisons made during merging depends on how the two sorted halves interleave: if one half is entirely smaller than the other, only about n/2 comparisons are needed for that merge, whereas interleaved data can require up to n-1 comparisons. Therefore merge sort's running time varies by a constant factor depending on the input order. Insertion sort is highly input-dependent: O(n) for already sorted input and $O(n^2)$ for reverse-sorted input. Quick sort is also highly input-dependent: it can degrade to $O(n^2)$ for already sorted input with a poor pivot choice. Hence Selection Sort is the algorithm whose running time is least dependent on the initial ordering. The primary attempt and verifier incorrectly selected Merge Sort by focusing on the invariance of its asymptotic complexity while overlooking that Selection Sort's comparison count is exactly constant regardless of input order. The standard answer to this classic GATE question is Selection Sort.
Reviewed by ISRO IQ Editorial Team.