Data Structures and Algorithms
The (name, score) records (A, 80), (B, 70), (C, 80), (D, 70) are in this order. If they are sorted by score in ascending order with a stable sort, in what order do the names appear?
- AB, D, A, C
- BD, B, A, C
- CB, D, C, A
Show answer and explanation
Answer: A. B, D, A, C
A stable sort keeps elements with the same key (here, the score) in their original relative order. B and D, both with 70, stay in the order B, D, and A and C, both with 80, stay in the order A, C, giving B, D, A, C. Bubble sort, insertion sort and merge sort are stable, while selection sort, quicksort and heapsort are generally not. With a stable sort you can sort by several keys, for example sorting by name first and then by score.
- A. Correct. Records with the same score keep their original order (B before D, A before C).
- B. B and D, both with 70, are in the reverse of their original order.
- C. A and C, both with 80, are in the reverse of their original order.