JIYIK CN >

Current Location:Home > Learning > PROGRAM > Java >

Implementing a Min Heap in Java

Author:JIYIK Last Updated:2025/04/14 Views:

A min heap is a heap in which every internal node is less than or equal to the value of its child nodes. We will see in the following points how to implement a min heap with and without using a library.


Minimal heap implementation in Java without using libraries

In this example, we see the implementation without using any library. Here, we have created a class JavaMinHeapin which we have created three instance variables HeapArraywhich is an intarray of type which will hold all the values ​​of the heap, sizeis the size of the heap, maxSizestores HeapArraythe maximum size of . We have also created a variable intof type and initialized it to 1.staticFRONT

maxSizeWe take as a parameter in the constructor and store it maxSizein the instance variable . We initialize with 0 sizeand an array maxSize + 1of size with . We store the minimum value of at the first index of .intHeapArrayIntegerHeapArray

Now we create methods to perform operations on the heap. parent()The function takes positionas a parameter and returns the parent of the node at the position passed. Then we create leftChild(), which returns the left child of the position received as a parameter. The same is true for the right child of the node rightChild()using .(2 * position) + 1

isLeaf()Checks if a node is a leaf node, which means it has any child nodes. swapNodes()is a method that swaps fposthe value of the node at position with the value of at position spos. In the method, we create a tempvariable and initialize it HeapArraywith the position of fposand store the value HeapArrayof sposinto HeapArray[fpos]. Now we tempstore the value of HeapArray[spos]in .

convertToMinHeap()We use isLeafto check if the position received as a parameter is a leaf, if not, we check HeapArrayif the current value of the position is greater than the left or right child. We then check if the left child is less than the right child, if so, we use swapNodes()to swap the nodes and positionpass positionand the left child at . We again use convertToMinHeap()to convert the received left child node into a min-heap.

We insert()insert the value into the min-heap using . In insert(), if the array reaches maxSize, we return without inserting; if not, we ++sizetake the position at and insert the received element HeapArray[++size]. We put 尺寸into 当前. If 当前the element at position is smaller than its parent, we create a cycle and swap the nodes.

To print a min heap, we create printheap()and loop through it HeapArray, where the parent is at ithposition , the left child is at 2 * iposition , and the right child is at 2 * i + 1position . In main()the function, we insert()insert an element in the heap using .

public class JavaMinHeap {
  private final int[] HeapArray;
  private int size;
  private final int maxsize;

  private static final int FRONT = 1;

  public JavaMinHeap(int maxsize) {
    this.maxsize = maxsize;
    this.size = 0;
    HeapArray = new int[this.maxsize + 1];
    HeapArray[0] = Integer.MIN_VALUE;
  }

  private int parent(int position) {
    return position / 2;
  }

  private int leftChild(int position) {
    return (2 * position);
  }

  private int rightChild(int position) {
    return (2 * position) + 1;
  }

  private boolean isLeaf(int position) {
    if (position >= (size / 2) && position <= size) {
      return true;
    }
    return false;
  }

  private void swapNodes(int fpos, int spos) {
    int temp;
    temp = HeapArray[fpos];
    HeapArray[fpos] = HeapArray[spos];
    HeapArray[spos] = temp;
  }

  private void convertToMinHeap(int position) {
    if (!isLeaf(position)) {
      if (HeapArray[position] > HeapArray[leftChild(position)]
          || HeapArray[position] > HeapArray[rightChild(position)]) {
        if (HeapArray[leftChild(position)] < HeapArray[rightChild(position)]) {
          swapNodes(position, leftChild(position));
          convertToMinHeap(leftChild(position));
        } else {
          swapNodes(position, rightChild(position));
          convertToMinHeap(rightChild(position));
        }
      }
    }
  }

  public void insert(int element) {
    if (size >= maxsize) {
      return;
    }
    HeapArray[++size] = element;
    int current = size;

    while (HeapArray[current] < HeapArray[parent(current)]) {
      swapNodes(current, parent(current));
      current = parent(current);
    }
  }

  public void printHeap() {
    for (int i = 1; i <= size / 2; i++) {
      System.out.println("PARENT : " + HeapArray[i]);

      System.out.println("--LEFT CHILD : " + HeapArray[2 * i]);

      System.out.println("--RIGHT CHILD : " + HeapArray[2 * i + 1]);
      System.out.println();
    }
  }

  public static void main(String[] arg) {
    System.out.println("The Min Heap is ");
    JavaMinHeap minHeap = new JavaMinHeap(10);
    minHeap.insert(10);
    minHeap.insert(2);
    minHeap.insert(7);
    minHeap.insert(15);
    minHeap.insert(90);
    minHeap.insert(19);
    minHeap.insert(8);
    minHeap.insert(22);
    minHeap.insert(9);

    minHeap.printHeap();
  }
}

Output:

The Min Heap is 
PARENT : 2
--LEFT CHILD : 9
--RIGHT CHILD : 7

PARENT : 9
--LEFT CHILD : 10
--RIGHT CHILD : 90

PARENT : 7
--LEFT CHILD : 19
--RIGHT CHILD : 8

PARENT : 10
--LEFT CHILD : 22
--RIGHT CHILD : 15

PriorityQueueImplementing a minimum heap in Java

In this program, we use the for creating maximum and minimum heap PriorityQueue. PriorityQueueMultiple methods are provided like add()Insert an element into a queue, peek()Get the head of the queue and remove it, poll()Also retrieve the head of the queue but don't remove it. contains()Checks if the element specified by it is in the queue. remove()Removes the specified element.

We combine PriorityQueueall the functionality of to create and perform min-heap operations. First, we new PriorityQueue()create an empty object Integerof type using . Then we use the method to add our elements. To print and remove the head of the queue, we call to print 10 . We then use the enhanced to print all the elements of the queue. Now we call to print and remove 10. We then remove an element from the queue. We use the returned by to check if the element is in the queue. Finally, to print the remaining values, we convert the queue into an array using .priorityQueueadd()priorityQueue.peek()forpoll()booleancontains()toArray()

import java.util.*;

public class JavaMinHeap {
  public static void main(String[] args) {
    PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();

    priorityQueue.add(10);
    priorityQueue.add(15);
    priorityQueue.add(25);
    priorityQueue.add(200);

    System.out.println("The head value using peek(): " + priorityQueue.peek());

    System.out.println("The queue elements: ");
    for (Integer integer : priorityQueue) System.out.println(integer);

    priorityQueue.poll();
    System.out.println("After removing the head element using poll(): ");
    for (Integer integer : priorityQueue) System.out.println(integer);

    priorityQueue.remove(25);
    System.out.println("After removing 25 with remove(): ");
    for (Integer integer : priorityQueue) System.out.println(integer);

    boolean b = priorityQueue.contains(15);
    System.out.println("Check if priorityQueue contains 15 using contains():  " + b);

    Object[] arr = priorityQueue.toArray();
    System.out.println("Values in array: ");
    for (Object o : arr) System.out.println("Value: " + o.toString());
  }
}

Output:

The head value using peek(): 10
The queue elements: 
10
15
25
200
After removing the head element using poll(): 
15
200
25
After removing 25 with remove(): 
15
200
Check if priorityQueue contains 15 using contains():  true
Values in array: 
Value: 15
Value: 200

Previous:Increasing the heap space in Java

Next: None

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Increasing the heap space in Java

Publish Date:2025/04/14 Views:190 Category:Java

In Java, the heap space is mainly used for garbage collection and allocating memory for objects. A default heap space is allocated when JVM is installed on our machine, but it may be different. The following points show how we can increase

Detecting EOF in Java

Publish Date:2025/04/14 Views:91 Category:Java

In this tutorial, we will see how to while detect EOF( End OF File ) in Java using a loop. We will also discuss developing a program that continues reading content until it reaches the end of a file. From a programming perspective, EOF is a

Get resource URL and content in Java

Publish Date:2025/04/14 Views:97 Category:Java

getResource() This tutorial will demonstrate how to use the function to get the resource URL and read the resource file in Java . getResource() Use the function to get the resource URL in Java We will use the method in Java getResource() to

Getting the host name in Java

Publish Date:2025/04/14 Views:78 Category:Java

In this tutorial, we will see how to get the IP address and host name using Java API. InetAddress Get the host name in Java using The package java.net contains classes for handling the IP address and host name of the current machine InetAdd

Get the IP address of the current device in Java

Publish Date:2025/04/14 Views:53 Category:Java

An Internet Protocol (IP) address is an identifier for each device connected to a TCP/IP network. This identifier is used to identify and locate nodes in the middle of communication. The IP address format, such as 127.0.0.0, is a human-read

Generate a random double value between 0 and 1 in Java

Publish Date:2025/04/14 Views:153 Category:Java

This article will introduce three methods to generate double random values ​​between 0 and 1 of primitive types. To demonstrate the randomness of the generated values, we will use a loop to generate ten random double values ​​betwee

Setting the seed of a random generator in Java

Publish Date:2025/04/14 Views:62 Category:Java

A seed is a number or vector assigned to a pseudo-random generator to generate the desired sequence of random values. If we pass the same seed, it will generate the same sequence. We usually assign the seed as the system time. In this way,

Switching on enumeration types in Java

Publish Date:2025/04/14 Views:96 Category:Java

This article explains how to use enum in Java . We will use statement switch with enum in two ways . switch In Java, we use traditional switch and case to perform enumeration operations. switch In this example, we SwitchEnum create an enume

How to delay for a few seconds in Java

Publish Date:2025/04/14 Views:131 Category:Java

This tutorial explains how to create program delays in Java and gives some sample code to understand it. There are several ways to create a time delay, such as TimeUnit.sleep() ,, ScheduleAtFixedRate() etc. Thread.sleep() Let's look at an e

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial