logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
instagramtwitterfacebookyoutubelinkedinmailgithubrss
Copyright © 2026 All rights reserved.
•
VIKI
Built with Vikramaditya Singh
Built with
VIKI - A posts created with Next.js and Tailwind.css
About
arrays
Arrays
Boyer-Moore Majority Vote Algorithm
Kadane’s Algorithm
Triple Reverse algorithm aka Reversal Algorithm
graph
Cycle detection
Graph
Topological Sort
Tree Traversal
heap
Binary Heap
Binomial Heap
Heap
linked-list
Cycle Detection
Linked List
Sorting
miscellaneous
Finding the majority element
Rotate array by K steps
numerical-algorithms
Finding If Number is Prime
GCD of two numbers
Performing Exponentiation
Prime Numbers
Randomising Data
partitioning
3. Max Consecutive Ones
Hoare'S Partition Scheme
Lomuto Partition Scheme
queue
Deques
Priority Queue
Queue
search
The Binary Search Master Guide
The Rotated Sorted Array Master Guide
sort
Bubble Sort
Counting Sort
Sorting
Insertion Sort
Merge Sort
Pigeon Hole Sort
Quick Sort
Selection Sort
stack
Monotonic Stack
Monotonic Stack
Stack
Reversing an Array
Stack
Tower of Hanoi
tree
Binary Tree Traversal
Centre of gravity
Diameter of Tree
Shortest Path
Algorithmic Pattern›heap

Binary Heap

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 TraversalNextBinomial Heap
CONTENTS
InsertDeleteMin/MaxReference&#x20;