Data Structures and Algorithms
Which sorting algorithm is O(n log n) even in the worst case and sorts with almost no extra memory such as a work array?
- AMerge sort
- BHeapsort
- CQuicksort
Show answer and explanation
Answer: B. Heapsort
Heapsort builds a binary heap inside the array and repeatedly swaps the maximum at the root with the last element and shrinks the heap, so it runs in O(n log n) even in the worst case and needs only a constant amount of extra memory. Merge sort is also O(n log n) in the worst case, but on an array it needs a work area proportional to n. Quicksort is O(n log n) on average and fast in practice, but depending on the pivot choice and the data it can degrade to O(n²). Note that heapsort compares elements that are far apart, so its cache efficiency is poor, and it is not stable.
- A. It is O(n log n) in the worst case, but on an array it needs a work area proportional to n.
- B. Correct. It is O(n log n) even in the worst case and sorts within the array itself.
- C. It is O(n log n) on average but O(n²) in the worst case.