Heap sort is n log n
Updated
build-heap O(n), then n extracts O(n log n). Total Θ(n log n). Ascending heapsort uses a max-heap and writes the next extreme at the shrinking end.
What to focus on
Not O(n). The extracts dominate. In-place: after extract, the old root sits at a[size] beyond the live heap. Extract sifts down with left 2*i+1 and right 2*i+2.
Worked examples
max-heap then extract
a = [1, 4, 9]- build max-heap [9, 4, 1]
- extract 9 → [4, 1 | 9]
- extract 4 → [1 | 4, 9]
Result: [1, 4, 9] sorted, Θ(n log n)
already extreme
a = [9, 4, 1]- already a max-heap
- still n extracts
Result: Θ(n log n) not O(n)
n=1
a = [7]- build no-op
- one extract leaves [7]
Result: [7]
Try it
Write heapsort(a). a is the array. Build a max-heap, then extract to the end. lastParent = Math.floor(n/2)-1. left(i)=2*i+1. right(i)=2*i+2. Return the sorted array. Print each extract. Label the total Θ(n log n). [1, 4, 9] → [1, 4, 9] [9, 4, 1] still does n extracts [7] stays
a is a non-empty array of 1–6 integers. Heapsort builds a max-heap then extracts.