V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Heap Sort

An in-place max heap shown as both an array and a tree

Turn the array into a priority structure

Heap Sort interprets the array as a complete binary tree. In a max heap, every parent is at least as large as its children, so the root is the maximum. Floyd's build starts at the last internal node and sifts each subtree downward.

Extract the root into the sorted suffix

Swap the root with the last heap element, shrink the heap, then sift the new root down until the max-heap invariant is restored. The array and tree tracks share element IDs, so every structural change stays synchronized.

7
6
5
10
9
8
4
3
2
1
7
6
5
10
9
8
4
3
2
1

Run sift-down from node 4 while building the max heap.

1function heapSort(a: number[]): number[] {
2 const n = a.length;
3 for (let i = Math.floor(n / 2) - 1; i >= 0; i--)
4 siftDown(a, i, n);
5 for (let end = n - 1; end > 0; end--) {
6 [a[0], a[end]] = [a[end], a[0]];
7 siftDown(a, 0, end);
8 }
9 return a;
10}
11function siftDown(a: number[], i: number, size: number) {
12 while (2 * i + 1 < size) {
13 let largest = i;
14 const l = 2 * i + 1, r = 2 * i + 2;
15 if (a[l] > a[largest]) largest = l;
16 if (r < size && a[r] > a[largest]) largest = r;
17 if (largest === i) break;
18 [a[i], a[largest]] = [a[largest], a[i]];
19 i = largest;
20 }
21}
n10
PhaseBuild heap
heapSize10
i4
left9
right-
largest4
swapCount0
1 / 57

Guaranteed bounds

Floyd heap construction is O(n). The following n - 1 extractions each cost at most O(log n), giving O(n log n) worst-case time and O(1) auxiliary space. Heap Sort is not stable.

Invariant: before each extraction, the active prefix is a max heap and the suffix is already in its final sorted order.

Compare its tree-based selection with Quick Sort partitioning.