VAlgorithm 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

Binary Heap

A complete tree that keeps one extreme value at the root

Tree shape from array indices

A binary heap is a complete binary tree usually stored in an array. For a node at index i, its children are at 2i + 1 and 2i + 2. No pointers are needed, and the complete shape keeps the height at O(log n).

Restore order along one path

In a max heap, every parent is at least as large as its children. Insertion appends a leaf and sifts it upward. Extracting the maximum moves the final leaf to the root and sifts it downward. Both repairs touch only one root-to-leaf path.

Try it
Array
90
70
80
40
60
30
50
0
1
2
3
4
5
6
Tree view of the same heap
90
70
80
40
60
30
50

Enter a value and insert it to watch it sift up from the array tail.

Costs: peek at the root in O(1); insert or extract in O(log n); build a heap bottom-up in O(n).

Heaps implement priority queues and power Heap Sort. Unlike a binary search tree, they do not keep the entire set in sorted order.

Optional analyticsAllow page views only? We do not send searches, algorithm inputs, playback, quiz, or sharing events.Privacy policy