sort.cny.shStart a race
Back to library
09 / 18Algorithm

Heap Sort

Build a max-heap, repeatedly extract the top.

StableIn-placeUnstable
BestO(n log n)
AverageO(n log n)
WorstO(n log n)
01How it works

Rearrange the array into a max-heap in place, then repeatedly swap the root to the back of the array and sift the new root down. Each extraction yields the next-largest value without allocating a single byte of extra memory.

02Best for

Environments that need a guaranteed O(n log n) worst case with zero extra memory — game engines, kernels, embedded schedulers, anything real-time. Also the foundation of priority queues.

03Avoid when

You need stability or the best average-case speed on random data. Cache behavior is poor compared to quicksort because the sift jumps around the array.