Implement a Binary Heap in Java
Last Updated :
30 May, 2024
A Binary Heap is a Data Structure that takes the form of a binary tree but it is implemented by using an Array. It is primarily used to efficiently manage a collection of elements with priority-based operations like priority queue we have two types of binary heaps namely Min Heap and Max Heap.
Basically, the Min-Heap ensures the smallest element in the list is at the root, whereas the Max-Heap places the largest element at the root.

Organization of a Binary Heap:
The Binary Heap is completely a Binary Tree, Meaning that all levels are fully filled except perhaps the last which is filled from left to right. This Structure allows binary heaps to be efficiently implemented in an array. And Given an index at i.
- The Parent node is at index (i-2)/2
- The left child is at index 2* i + 1
- The left child is at index 2* i + 2
These relationship allow easily navigation between parent and child nodes without needing additional reference, ensuring efficient operations.
Basic Operations with Time and Space Complexity
Operation
| Description
| Complexity
|
---|
Insertion
| Add the new element to the end of the tree. Restore the heap property by heapifying up and swapping newly added element with Its parent if needed.
| Time Complexity O(log n) where n is the number of elements in the heap.
|
---|
Extract Min or Max for max-heap:
| Replace the root with the last element in the heap. Restore the heap property by heapifying down swapping with the smaller or larger child to maintain the property.
| Time Complexity O(log n).
|
---|
Peek (Get Min or Max)
| Return the root element without modifying the heap
| Time Complexity is O(1)
|
---|
Heapify
| Given an array transform it into a heap
| Time Complexity is O(n)
|
---|
Space Complexity:
The space complexity is O(n) and since the data is stored in an array of size proportional to the number of elements
Binary Heap Implementation
The Binary Heap is implemented by using an Array, with operations like insertion and deletion designed to maintain the heap invariant property This property varies based on heap type.
- In a Min-Heap, each parent node is smaller than its children
- In a Max-Heap, each parent node is larger than its children
Program to Implement Min Heap
Below is the program to implement Min Heap:
Java
// Java Program to Implement Min Binary Heap
import java.util.Arrays;
public class BinaryHeap {
// Array representation of the heap
private int[] heap;
// Number of elements currently in the heap
private int size;
// Maximum number of elements the heap can hold
private int capacity;
// Constructor to initialize the heap with a given capacity
public BinaryHeap(int capacity) {
this.capacity = capacity;
this.heap = new int[capacity];
this.size = 0;
}
// Method to get the index of the
// parent of a given node
private int parent(int i) {
return (i - 1) / 2;
}
// Method to get the index of the
// left child of a given node
private int leftChild(int i) {
return 2 * i + 1;
}
// Method to get the index of the
// right child of a given node
private int rightChild(int i) {
return 2 * i + 2;
}
// Method to swap two elements in the heap array
private void swap(int i, int j) {
int temp = heap[i];
heap[i] = heap[j];
heap[j] = temp;
}
// Method to resize the heap array when capacity is reached
private void resize() {
capacity *= 2;
heap = Arrays.copyOf(heap, capacity);
}
// Method to insert a new value into the heap
public void insert(int value) {
if (size >= capacity) {
// Resize the heap if capacity is reached
resize();
}
// Place the new value at the end of the heap
heap[size] = value;
// Index of the newly added element
int current = size;
// Increase the size of the heap
size++;
// Restore the heap property by "heapifying up"
while (current > 0 && heap[current] < heap[parent(current)]) {
// Swap with the parent if smaller
swap(current, parent(current));
// Move up to the parent's position
current = parent(current);
}
}
// Method to restore the heap property by
// "heapifying down" from a given index
private void heapifyDown(int i) {
// Assume the current index is the smallest
int smallest = i;
// Get the left child index
int left = leftChild(i);
// Get the right child index
int right = rightChild(i);
// If the left child is smaller than the current
// smallest element, update smallest
if (left < size && heap[left] < heap[smallest]) {
smallest = left;
}
// If the right child is smaller than the current
// smallest element, update smallest
if (right < size && heap[right] < heap[smallest]) {
smallest = right;
}
// If the smallest element is not the current
// element, swap and continue heapifying down
if (smallest != i) {
swap(i, smallest);
heapifyDown(smallest);
}
}
// Method to extract the minimum element from the heap
public int extractMin() {
if (size == 0) {
// Check if the heap is empty
throw new RuntimeException("Heap is empty!");
}
// The root of the heap is the minimum element
int min = heap[0];
// Replace the root with the last element in the heap
heap[0] = heap[size - 1];
size--;
// Restore the heap property by "heapifying down" from the root
heapifyDown(0);
// Return the extracted minimum element
return min;
}
// Method to print the current
// state of the heap
public void printHeap() {
// Print the heap elements as
// an array, up to the current size
System.out.println(Arrays.toString(Arrays.copyOf(heap, size)));
}
// Main method to demonstrate the
// usage of the BinaryHeap class
public static void main(String[] args) {
// Create a BinaryHeap with an initial capacity of 10
BinaryHeap bh = new BinaryHeap(10);
// Insert elements into the heap
bh.insert(10);
bh.insert(5);
bh.insert(30);
bh.insert(3);
bh.insert(8);
// Print the heap after inserting elements
System.out.println("Heap after inserting elements:");
bh.printHeap();
// Extract the minimum element and print it
System.out.println("Extracted minimum: " + bh.extractMin());
// Print the heap after extracting the minimum element
System.out.println("Heap after extracting the minimum:");
bh.printHeap();
}
}
OutputHeap after inserting elements:
[3, 5, 30, 10, 8]
Extracted minimum: 3
Heap after extracting the minimum:
[5, 8, 30, 10]
Applications of Binary Heap
Binary heaps are widely used in various applications like
- Priority Queues: Efficiently managed priority based operations like insertion, deletion and other operations.
- Heap Sort: A popular sorting algorithm that uses binary heaps
- Graph Algorithms: Binary heaps are used in Dijkstra's shortest path and Prim's minimum spanning tree algorithms
- Task Scheduling: Managing tasks with different priorities.
Conclusion
Binary data structure are versatile data structures that are offer efficient operations for priority based operations. Their array based implementation and lo scale operations make them suitable for a range applications from sorting algorithms to graph traversal. Implementing a binary heap in Java involves careful handling of operations to maintain the heap property By understanding the organization and operations of binary heaps, you can leverage their efficiency in a variety of scenarios.
Similar Reads
Implementing a Binary Tree in Java
A binary tree is a hierarchical data structure composed of the nodes. Each node contains the value and references to its left child node and right child node, which are also binary trees that are possibly null. The structure resembles the tree with the nodes branching out from a central root, where
5 min read
Heap implementation in Java
A heap is a binary tree-based data structure that adheres to a heap property. In a heap, every parent node has a specific relationship with its children: in a max-heap, each parent is greater than or equal to its children, while in a min-heap, each parent is less than or equal to its children. Heaps
8 min read
Implement Heap in C++
A heap is a type of tree data structure where each node is either greater than or equal to or less than or equal to the values of its children. Based on this property, heaps are classified into two types: Min Heap: Each node is less than or equal to the values of its children.Max Heap: Each node is
7 min read
C++ Program to Implement Binary Heap
A binary heap is a complete binary tree that satisfies the heap property. The heap property states that for a max-heap, every parent node has a value greater than or equal to its children, and for a min-heap, every parent node has a value less than or equal to its children. Binary heaps are commonly
8 min read
C Program to Implement Binary Heap
Binary heaps are the most fundamental data structures which are used in various algorithms. They are mostly used in implementing priority queues and also in heapsort. They are tree-based data structures that satisfy heap order property. In this article, we will study the implementation of Binary hea
6 min read
Binary Tree (Array implementation)
Given an array that represents a tree in such a way that array indexes are values in tree nodes and array values give the parent node of that particular index (or node). The value of the root node index would always be -1 as there is no parent for root. Construct the standard linked representation o
6 min read
Java Program to Implement Fibonacci Heap
Fibonacci heaps are an effective data structure that may be used to create priority queues. They provide better reduced time complexity than conventional binary heaps for important operations like insertion, deletion, and minimal element finding. This article explores the topic of Java Fibonacci hea
5 min read
C++ Program to Implement Binomial Heap
A binomial heap is a collection of the binomial trees that are linked together. Each binomial tree in the heap has a node structure where the key of a node is greater than or equal to the key of its parent. It is an extension of Binary Heap that allows us to perform union or merge operation faster m
9 min read
C Program to Implement Binomial Heap
Binomial Heap is a specific type of heap data structure that finds its roots in the Binomial Tree. Itâs a collection of binomial trees, each adhering to the min-heap property, where the parent nodeâs key is less than or equal to its childrenâs keys. This structure is particularly efficient for imple
4 min read
Binary Heap in Python
A Binary Heap is a complete Binary Tree that is used to store data efficiently to get the max or min element based on its structure. A Binary Heap is either a Min Heap or a Max Heap. In a Min Binary Heap, the key at the root must be minimum among all keys present in a Binary Heap. The same property
3 min read