1import java.util.PriorityQueue;
2
3public class MaxHeapWithPriorityQueue {
4
5 public static void main(String args[]) {
6 // create priority queue
7 PriorityQueue<Integer> prq = new PriorityQueue<>(Comparator.reverseOrder());
8
9 // insert values in the queue
10 prq.add(6);
11 prq.add(9);
12 prq.add(5);
13 prq.add(64);
14 prq.add(6);
15
16 //print values
17 while (!prq.isEmpty()) {
18 System.out.print(prq.poll()+" ");
19 }
20 }
21
22}
1import heapq
2
3Since the built in heapq library is a minheap, multiply your values by -1
4and it will function as a max heap. Just remeber that all your numbers
5have been inverted.
1def min_heapify(A,k):
2 l = left(k)
3 r = right(k)
4 if l < len(A) and A[l] < A[k]:
5 smallest = l
6 else:
7 smallest = k
8 if r < len(A) and A[r] < A[smallest]:
9 smallest = r
10 if smallest != k:
11 A[k], A[smallest] = A[smallest], A[k]
12 min_heapify(A, smallest)
13
14def left(k):
15 return 2 * k + 1
16
17def right(k):
18 return 2 * k + 2
19
20def build_min_heap(A):
21 n = int((len(A)//2)-1)
22 for k in range(n, -1, -1):
23 min_heapify(A,k)
24
25A = [3,9,2,1,4,5]
26build_min_heap(A)
27print(A)
28
1def max_heapify(A,k):
2 l = left(k)
3 r = right(k)
4 if l < len(A) and A[l] > A[k]:
5 largest = l
6 else:
7 largest = k
8 if r < len(A) and A[r] > A[largest]:
9 largest = r
10 if largest != k:
11 A[k], A[largest] = A[largest], A[k]
12 max_heapify(A, largest)
13
14def left(k):
15 return 2 * k + 1
16
17def right(i):
18 return 2 * k + 2
19
20def build_max_heap(A):
21 n = int((len(A)//2)-1)
22 for k in range(n, -1, -1):
23 max_heapify(A,k)
24
25A = [3,9,2,1,4,5]
26build_max_heap(A)
27print(A)