Worst case time complexity of heap sort for n elements
- (A)
O(nlogn)
- (B)
O(logn)
- (C)
O(n^2)
- (D)
O(n)
Worst case time complexity of heap sort for n elements
O(nlogn)
O(logn)
O(n^2)
O(n)
ANSWER
The worst-case time complexity of heap sort is , which is option (A).
Official answer: ASource: ISRO's revised and final answer key of 16 February 2024
Heap sort has two phases: build a max-heap from the elements, then repeatedly extract the maximum.
Building the heap bottom-up (sift down from node to the root) costs in the worst case.
Each of the extractions swaps the root with the last element of the heap and sifts the new root down. A sift-down moves down at most the height of the heap, which is at most , so each extraction costs in the worst case.
Total worst-case time: . This upper bound holds for every input, so the worst case is .
The bound is also tight: for distinct keys, the extraction phase needs on the order of comparisons, so the worst case is .
Other options: and are too small, since any comparison sort needs comparisons in the worst case. is a valid but loose upper bound; it is the worst case of simple quicksort, not of heap sort.
KEY IDEA
Heap sort builds the heap in and then performs extractions, each a sift-down of at most levels. The total is for every input, and it needs no extra array.
WATCH OUT FOR
Confusing heap sort with quicksort and choosing . Quicksort with a poor pivot can reach , but heap sort's sift-down never exceeds the heap height, so its worst case stays at . Another slip is choosing because heap construction alone is linear.
From the ISRO CS 2023 paper. Every question of this paper · The full paper (PDF, ISRO) · All 3 ISRO Sorting & hashing questions, with notes