Skip to main content

Command Palette

Search for a command to run...

Code of heap

Published
•2 min read•View as Markdown

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:

  1. Adding Elements:

    • Numbers like 50, 20, 30, 10, 5 are added to the heap.

    • The heap arranges them to keep the smallest number (5) at the top.

  2. 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

  1. Priority Queue:

    • Imagine tasks like “clean room” or “study for exams.” A heap lets the most important task get done first.
  2. Pathfinding Algorithms:

    • Google Maps uses heaps to find the shortest route.
  3. Sorting:

    • You can use heaps to sort numbers, known as Heap Sort.

More from this blog

codebhghvhv

34 posts