Answers for "max heap example"

5

max heap java

import java.util.PriorityQueue;

public class MaxHeapWithPriorityQueue {

    public static void main(String args[]) {
        // create priority queue
        PriorityQueue<Integer> 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()+" ");
        }
    }

}
Posted by: Guest on August-02-2020
2

max heap python

import heapq

Since the built in heapq library is a minheap, multiply your values by -1
and it will function as a max heap. Just remeber that all your numbers 
have been inverted.
Posted by: Guest on August-19-2021
1

example of a min heap

10                      10
         /      \               /       \  
       20        100          15         30  
      /                      /  \        /  \
    30                     40    50    100   40
Posted by: Guest on May-29-2021
0

Max Heap Python

def max_heapify(A,k):
    l = left(k)
    r = right(k)
    if l < len(A) and A[l] > A[k]:
        largest = l
    else:
        largest = k
    if r < len(A) and A[r] > A[largest]:
        largest = r
    if largest != k:
        A[k], A[largest] = A[largest], A[k]
        max_heapify(A, largest)

def left(k):
    return 2 * k + 1

def right(i):
    return 2 * k + 2

def build_max_heap(A):
    n = int((len(A)//2)-1)
    for k in range(n, -1, -1):
        max_heapify(A,k)

A = [3,9,2,1,4,5]
build_max_heap(A)
print(A)
Posted by: Guest on July-09-2021

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language