Algorithms · Visualized
Heap Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Heap Sort first turns the array into a max-heap (a binary tree stored in an array where every parent is bigger than its children, so the largest value sits at the root). Time: O(n log n) average, O(n log n) worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Heap Sort
SortingHeap Sort first turns the array into a max-heap (a binary tree stored in an array where every parent is bigger than its children, so the largest value sits at the root). It then repeatedly pulls the root (the largest remaining value) out to the end of the array and re-heapifies what's left.
How Heap Sort Works
- Build a max-heap from the input array — the biggest element ends up at index 0.
- Swap the root (largest element) with the last element of the heap.
- Shrink the heap's boundary by one, excluding the element you just placed at the end.
- 'Sift down' the new root so the max-heap property is restored.
- Repeat swapping the new root to the current end and sifting down until the heap has one element left — the array is now sorted.
Heap Sort Worked Example
Input: [4, 10, 3, 5, 1]
Build max-heap → [10,5,3,4,1]. Swap root 10 with last element → [1,5,3,4,10], heap shrinks to [1,5,3,4]. Sift down → [5,4,3,1]. Swap 5 with last of heap → [1,4,3,5,10], heap = [1,4,3]. Sift down → [4,1,3]. Swap 4 to end → [3,1,4,5,10], heap=[3,1]. Sift down→[3,1]. Swap→[1,3,4,5,10]. Final: [1,3,4,5,10].
def heap_sort(a):
import heapq
h = a[:]
heapq.heapify(h)
return [heapq.heappop(h) for _ in range(len(h))]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Heap Sort Time & Space Complexity
When to Use Heap Sort
- When you need guaranteed O(n log n) performance with no extra memory, unlike merge sort.
- Priority queue implementations, and problems needing repeated access to the current maximum/minimum.
- Systems with strict, predictable time bounds (real-time systems).
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.