logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
ArraysBoyer-Moore Majority Vote AlgorithmKadane’s AlgorithmTriple Reverse algorithm aka Reversal Algorithm
Cycle detectionDijkstraDisjoint Set UnionGraphTopological SortTraversal algorithmsTree Traversal
Binary HeapBinomial HeapHeap
Cycle DetectionLinked ListSorting
Finding the majority elementRotate array by K steps
Finding If Number is PrimeGCD of two numbersPerforming ExponentiationPrime NumbersRandomising Data
3. Max Consecutive OnesHoare'S Partition SchemeLomuto Partition Scheme
DequesPriority QueueQueue
The Binary Search Master GuideThe Rotated Sorted Array Master Guide
Bubble SortCounting SortInsertion SortMerge SortPigeon Hole SortQuick SortSelection Sort
Monotonic StackMonotonic StackStackReversing an ArrayStackTower of Hanoi
Binary Tree TraversalCentre of gravityDiameter of TreeShortest Path
Algorithmic Pattern/heap

Binary Heap

2 min read
On this pageInsert
InsertDeleteMin/MaxReference 

A complete binary tree can be uniquely represented by storing its level order traversal in an array.

We skip the index zero cell of the array for the convenience of implementation so the the root is the second item in the array.

Consider kthk^{\text{th}}kth element of the array, the

  • its left child is located at 2∗k2*k2∗k index
  • its right child is located at 2∗k+12*k+12∗k+1 index
  • its parent is located at k2\frac{k}{2}2k​ index

# Insert

The new element is appended to the end of the heap (as the last element of the array).

  • The heap property is repaired by comparing the added element with its parent and moving the added element up a level (swapping positions with the parent).
  • The comparison is repeated until the parent is larger than or equal to the percolating element.
public void insert(Comparable x)
{
	if(size == heap.length - 1) doubleSize();
 
	//Insert a new item to the end of the array
	int pos = ++size;
 
	//Percolate up
	for(; pos > 1 && x.compareTo(heap[pos/2]) < 0; pos = pos/2 )
		heap[pos] = heap[pos/2];
 
	heap[pos] = x;
}

The worst-case runtime of the algorithm is O(log⁡n)\text{O}(\log{n})O(logn), since we need at most one swap on each level of a heap on the path from the inserted node to the root.\

# DeleteMin/Max

The minimum element can be found at the root, which is the first element of the array.

We remove the root and replace it with the last element of the heap and then restore the heap property by percolating down.

The worst-case runtime is O{log n).\

# Reference

  • Binary Heaps
  • Binary Heap Implementation
←PreviousTree TraversalNext→Binomial Heap

On this page

InsertDeleteMin/MaxReference&#x20;