Code of heap
Java Code Example: Min Heap
Let’s create a Min Heap in Java using PriorityQueue.
import java.util.PriorityQueue;
public class MinHeapExample {
public static void main(String[] args) {
// Create a Min Heap
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
// Add elements to the heap
minHeap.add(50);
minHeap.add(20);
minHeap.add(30);
minHeap.add(10);
minHeap.add(5);
// Display the heap (not fully sorted, but smallest is at the top)
System.out.println("Min Heap: " + minHeap);
// Remove elements one by one (smallest first)
System.out.println("Removing elements in order:");
while (!minHeap.isEmpty()) {
System.out.println(minHeap.poll());
}
}
}
Output:
Min Heap: [5, 10, 30, 50, 20]
Removing elements in order:
5
10
20
30
50
How This Code Works:
Adding Elements:
Numbers like
50, 20, 30, 10, 5are added to the heap.The heap arranges them to keep the smallest number (5) at the top.
Removing Elements:
poll()removes the top element (smallest) and adjusts the heap to bring the next smallest number to the top.
Java Code Example: Max Heap
To create a Max Heap, we can use PriorityQueue with a custom comparator.
import java.util.Collections;
import java.util.PriorityQueue;
public class MaxHeapExample {
public static void main(String[] args) {
// Create a Max Heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
// Add elements to the heap
maxHeap.add(50);
maxHeap.add(20);
maxHeap.add(30);
maxHeap.add(10);
maxHeap.add(5);
// Display the heap (largest is at the top)
System.out.println("Max Heap: " + maxHeap);
// Remove elements one by one (largest first)
System.out.println("Removing elements in order:");
while (!maxHeap.isEmpty()) {
System.out.println(maxHeap.poll());
}
}
}
Output:
Max Heap: [50, 20, 30, 10, 5]
Removing elements in order:
50
30
20
10
5
Common Uses of Heaps
Priority Queue:
- Imagine tasks like “clean room” or “study for exams.” A heap lets the most important task get done first.
Pathfinding Algorithms:
- Google Maps uses heaps to find the shortest route.
Sorting:
- You can use heaps to sort numbers, known as Heap Sort.