AlgoLab

O(n log n)·O(1) space·not stable
645559896316373459948511843281951114277

Starting heap sort on an array of 20 items.

Starting heap sort on an array of 20 items.
  1. 1build a max-heap by sifting every parent down, starting from the middle of the array
  2. 2compare a value with its largest child to see which is bigger
  3. 3if a child is larger, swap it with its parent and keep sifting down
  4. 4swap the largest remaining value, the heap root, with the last value in the heap
  5. 5shrink the heap by one and sift the new root back down
  6. 6the array is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n log n)
AverageO(n log n)
WorstO(n log n)
Extra spaceO(1)
StableNo
n log₂ n at n=20 predicts 86; this run took 0.

Heap sort

Heap sort first arranges the array into a max-heap: a binary tree stored in the array itself, where every parent is at least as large as its children. It then repeatedly swaps the root — the largest remaining value — with the last unsorted position, and restores the heap property on the shrunken heap.

When it is the right choice

Heap sort is the right choice when a guaranteed O(n log n) worst case and O(1) extra space both matter, such as in memory-constrained settings, since unlike quicksort it has no input that makes it degrade and unlike merge sort it needs no auxiliary buffer. It is rarely chosen otherwise, because its constant factors make it slower in practice than a well-implemented quicksort, and it is not stable.

How it works

Worth noticing

Cost

Best
O(n log n)
Average
O(n log n)
Worst
O(n log n)
Extra space
O(1)
Stable
No

Worth comparing

All algorithms