- 2070 Magh · 2+4+2 marks
Stable vs unstable sorting; heap
Short answer
Stable sorting preserves original relative order of equal keys (e.g., bubble sort); unstable does not (e.g., heap sort). Building a max-heap for 8,10,5,12,14,18,19 by insertion yields array 19,12,18,8,10,5,14. Heap sort complexity is O(n log n) in all cases.
Differentiate between stable and unstable sorting with example. Construct a heap for the following data: 8, 10, 5, 12, 14, 18, 19. What is the time complexity for sorting the unsorted elements using heap-sort?
Stable and unstable sorting
A sorting algorithm is stable if records with equal keys stay in the same relative order after sorting. An unstable algorithm may change that order.
Example: sort by marks the records (Ram, 80), (Sita, 90), (Hari, 80).
- Stable result: (Ram, 80), (Hari, 80), (Sita, 90). Ram is still before Hari.
- Unstable result: (Hari, 80), (Ram, 80), (Sita, 90). Their order has changed.
| Stable | Unstable |
|---|---|
| Bubble, insertion, merge, counting, radix sort | Selection, quick, heap, shell sort |
| Needed when sorting on multiple keys in succession | Equal keys may be reordered |
Heap for 8, 10, 5, 12, 14, 18, 19 (max-heap by successive insertion)
| Step | Insert | Array (heap) after step | Moves |
|---|---|---|---|
| 1 | 8 | 8 | none |
| 2 | 10 | 10, 8 | 10↔8 |
| 3 | 5 | 10, 8, 5 | none |
| 4 | 12 | 12, 10, 5, 8 | 12↔8, 12↔10 |
| 5 | 14 | 14, 12, 5, 8, 10 | 14↔10, 14↔12 |
| 6 | 18 | 18, 12, 14, 8, 10, 5 | 18↔5, 18↔14 |
| 7 | 19 | 19, 12, 18, 8, 10, 5, 14 | 19↔14, 19↔18 |
19
/ \
12 18
/ \ / \
8 10 5 14
Array form: 19, 12, 18, 8, 10, 5, 14. Every parent is greater than or equal to its children. (A min-heap built the same way would be 5, 10, 8, 12, 14, 18, 19.)
Time complexity of heap sort
Building the heap takes O(n); each of the n − 1 extractions needs a sift-down of O(log n). So the time for sorting is O(n log n) in the best, average and worst cases (space O(1)).
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Heap sort on 37, 33, 26, 92, ... · Data Structure and Algorithm, chapter 7
- Heap tree insertion and heap sort · Data Structure and Algorithm, chapter 7
- Heap sort with example · Data Structure and Algorithm, chapter 7
- Radix sort on 25, 57, 48, 37, ... · Data Structure and Algorithm, chapter 7
- Algorithm for an exchange sort · Data Structure and Algorithm, chapter 7 · asked 2×
- Merge and radix sort on 142, 523, ... · Data Structure and Algorithm, chapter 7
- Stable/unstable systems; test stability · Data Communication, chapter 2
- K-map Σ(1,2,3,8,9,10,11,14)+d(0,4,12), NAND · Digital Logic, chapter 3 · asked 5×
- Class C pool for 10, 12, 8, 14 · Computer Networks and Security, chapter 4 · asked 2×
- Σ(0,1,3,6,10,12,14) using 8×1 MUX · Digital Logic, chapter 4