max heap implementation code example

Example 1: min heap in c++

priority_queue , greater> minHeap;

Example 2: max heap java

import java.util.PriorityQueue;

public class MaxHeapWithPriorityQueue {

    public static void main(String args[]) {
        // create priority queue
        PriorityQueue prq = new PriorityQueue<>(Comparator.reverseOrder());

        // insert values in the queue
        prq.add(6);
        prq.add(9);
        prq.add(5);
        prq.add(64);
        prq.add(6);

        //print values
        while (!prq.isEmpty()) {
            System.out.print(prq.poll()+" ");
        }
    }

}

Example 3: max heap in c++

priority_queue  maxHeap;

Example 4: min max heap java

// min heap: PriorityQueue implementation from the JDK
PriorityQueue prq = new PriorityQueue<>();

// max heap: PriorityQueue implementation WITH CUSTOM COMPARATOR PASSED
// Method 1: Using Collections (recommended)
PriorityQueue prq = new PriorityQueue<>(Collections.reverseOrder());
// Method 2: Using Lambda function (may cause Integer Overflow)
PriorityQueue prq = new PriorityQueue<>((a, b) -> b - a);

Example 5: max heap c++

#include 
using namespace std;
void max_heap(int *a, int m, int n) {
   int j, t;
   t = a[m];
   j = 2 * m;
   while (j <= n) {
      if (j < n && a[j+1] > a[j])
         j = j + 1;
      if (t > a[j])
         break;
      else if (t <= a[j]) {
         a[j / 2] = a[j];
         j = 2 * j;
      }
   }
   a[j/2] = t;
   return;
}
void build_maxheap(int *a,int n) {
   int k;
   for(k = n/2; k >= 1; k--) {
      max_heap(a,k,n);
   }
}
int main() {
   int n, i;
   cout<<"enter no of elements of array\n";
   cin>>n;
   int a[30];
   for (i = 1; i <= n; i++) {
      cout<<"enter elements"<<" "<<(i)<>a[i];
   }
   build_maxheap(a,n);
   cout<<"Max Heap\n";
   for (i = 1; i <= n; i++) {
      cout<

Tags:

Misc Example