Which one of the given sorting techniques does not change the relative order of elements...
Qualcomm technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Which one of the given sorting techniques does not change the relative order of elements with equal keys?
Show answer & explanation
A sorting algorithm is stable if it preserves the relative order of elements with equal keys. Insertion sort is stable because it only shifts elements to the right when inserting, never reordering equal elements. Quick sort, selection sort, and heap sort are all unstable because their comparison and swap operations can alter the relative positions of equal-valued elements.
Step-by-step Derivation:
Stability analysis of each algorithm:
Quick sort (A): Unstable. The partitioning process can move equal elements around arbitrarily based on pivot selection and partition positions.
Selection sort (B): Unstable. It finds the minimum element and swaps it with the current position, which can displace equal elements that appeared earlier.
Insertion sort (C): Stable. Elements are inserted into their correct position relative to already-sorted elements. Equal elements maintain their original relative order because insertion only happens when the current element is strictly less than the comparison element (using < not <=).
Heap sort (D): Unstable. The heap structure rearranges elements during heapify operations, causing equal elements to lose their original relative order.
Example: Sorting [(3, 'first'), (1, 'a'), (3, 'second'), (2, 'b')] by first element:
- Insertion sort result: [(1, 'a'), (2, 'b'), (3, 'first'), (3, 'second')] ✓ Stable
- Heap sort result: [(1, 'a'), (2, 'b'), (3, 'second'), (3, 'first')] ✗ Unstable