Heap Sort visualization
Build a max-heap, then repeatedly move the root (maximum) to the end and re-heapify.
The array is viewed as a complete binary tree: children of i live at 2i+1 and 2i+2. A max-heap keeps every parent ≥ its children, so the maximum sits at the root.
Swap the root with the last heap element, shrink the heap, and sift the new root down. Repeat n times — guaranteed O(n log n), in place.
Complexity
Time: best O(n log n), average O(n log n), worst O(n log n). Space: O(1). Difficulty: Advanced.
Pseudocode
procedure heapSort(A):
for i ← n/2−1 down to 0: siftDown(A, i, n)
for end ← n−1 down to 1:
swap(A[0], A[end]); siftDown(A, 0, end)
procedure siftDown(A, i, size):
largest ← max of i, 2i+1, 2i+2 (within size)
if largest ≠ i:
swap(A[i], A[largest]); siftDown(A, largest, size)More sorting algorithms
- Bubble Sort — Repeatedly swap adjacent out-of-order pairs; the largest value bubbles to the end each pass.
- Selection Sort — Find the minimum of the unsorted part and swap it to the front.
- Insertion Sort — Grow a sorted prefix by inserting each new value into its correct slot.
- Cocktail Shaker Sort — Bubble sort that alternates direction, moving large values right and small values left.
- Shell Sort — Insertion sort over shrinking gaps, so values travel long distances early.
- Merge Sort — Divide in half, sort each half recursively, then merge the two sorted halves.
- Quick Sort — Partition around a pivot so smaller values go left and larger go right, then recurse.
- Counting Sort — Count occurrences of each value, then rebuild the array from the counts.
- Radix Sort (LSD) — Sort by the ones digit, then tens, then hundreds — each pass is a stable bucket sort.