Lab 8 – Heaps and Priority Queues
Part 1 – A max binary heap¶
Task 1 – The class MaxBinaryHeap¶
public class MaxBinaryHeap {
private int[] heap;
private int heapSize;
public MaxBinaryHeap(int capacity) { /* ToDo */ }
public boolean isEmpty() { /* ToDo */ }
public boolean isFull() { /* ToDo */ }
public void printHeap() { /* ToDo: "Heap = 15-14-13-..." */ }
}🚩 Index 0 is not used: an array of
capacity + 1cells holds at mostcapacitykeys, so the heap is full whenheapSize == heap.length - 1. Withheap.length, inserting into a full heap would write past the end of the array.
Solution
private int[] heap; // heap[0] is not used
private int heapSize;
public MaxBinaryHeap(int capacity) {
heapSize = 0;
heap = new int[capacity + 1];
}
public boolean isEmpty() {
return heapSize == 0;
}
public boolean isFull() {
return heapSize == heap.length - 1; // index 0 is unused
}
public void printHeap() {
System.out.print("Heap = ");
for (int i = 1; i <= heapSize; i++)
System.out.print(heap[i] + "-");
System.out.println();
}Tasks 2 to 5 – Navigating the array¶
Return the index of the parent of node i, of its left child, of its right child, and of
the last parent of the heap.
private int parent(int i) { /* ToDo */ }
private int leftChild(int i) { /* ToDo */ }
private int rightChild(int i) { /* ToDo */ }
private int lastParent() { /* ToDo */ }Solution
private int parent(int i) {
return i / 2;
}
private int leftChild(int i) {
return 2 * i;
}
private int rightChild(int i) {
return 2 * i + 1;
}
private int lastParent() {
return heapSize / 2;
}Task 6 – Percolate up¶
Move the key at index i up while it is larger than its parent. Do not swap: keep the
key in temp, move parents down into the hole, and write temp once at the end.
private void PercolateUp(int i) {
// ToDo
}Solution
private void PercolateUp(int i) {
int temp = heap[i];
while (parent(i) > 0 && temp > heap[parent(i)]) {
heap[i] = heap[parent(i)]; // move the parent down
i = parent(i);
}
heap[i] = temp;
}Task 7 – Percolate down¶
Move the key at index i down while it is smaller than its larger child.
private int maxChild(int i) {
return heap[leftChild(i)] > heap[rightChild(i)] ? leftChild(i) : rightChild(i);
}
private void PercolateDown(int i) {
int child;
int temp = heap[i];
while (...) {
// ToDo
}
heap[i] = temp;
}Solution
private int maxChild(int i) {
return heap[leftChild(i)] > heap[rightChild(i)] ? leftChild(i) : rightChild(i);
}
private void PercolateDown(int i) {
int child;
int temp = heap[i];
while (leftChild(i) <= heapSize) {
if (rightChild(i) <= heapSize)
child = maxChild(i);
else
child = leftChild(i);
if (temp < heap[child])
heap[i] = heap[child]; // move the larger child up
else
break;
i = child;
}
heap[i] = temp;
}Task 8 – Insert¶
public void insert(int x) {
if (isFull()) {
System.out.println("Heap is full, No space to insert new element");
} else {
// ToDo
}
}Solution
public void insert(int x) {
if (isFull()) {
System.out.println("Heap is full, No space to insert new element");
} else {
heap[++heapSize] = x;
PercolateUp(heapSize);
}
}Task 9 – Remove the maximum (the root)¶
public int delete() {
if (isEmpty()) {
System.out.println("Heap is empty, No element to delete");
return -1;
} else {
// ToDo
}
}Solution
public int delete() {
if (isEmpty()) {
System.out.println("Heap is empty, No element to delete");
return -1;
} else {
int key = heap[1];
heap[1] = heap[heapSize];
heapSize--;
PercolateDown(1);
return key;
}
}Task 10 – Build a heap from an array: heapify¶
Add a constructor that copies an array into the heap (at positions 1 to ) and calls
Heapify(), which percolates down every parent, from the last one up to the root:
.
public MaxBinaryHeap(int[] input) {
// ToDo
Heapify();
}
public void Heapify() {
// ToDo
}Solution
public MaxBinaryHeap(int[] input) {
heapSize = input.length;
heap = new int[heapSize + 1];
for (int i = 1; i <= heapSize; i++)
heap[i] = input[i - 1];
Heapify();
}
public void Heapify() {
for (int i = lastParent(); i > 0; i--)
PercolateDown(i);
}Task 11 – Heap sort¶
Build a heap from the input, then remove the maximum times, filling the result from the end.
public static int[] sort(int[] input) {
MaxBinaryHeap m = new MaxBinaryHeap(input);
int[] res = new int[input.length];
// ToDo
return res;
}Solution
public static int[] sort(int[] input) {
MaxBinaryHeap m = new MaxBinaryHeap(input);
int[] res = new int[input.length];
for (int i = input.length - 1; i >= 0; i--)
res[i] = m.delete(); // the largest remaining goes last
return res;
}Task 12 – Test your heap¶
MaxBinaryHeap maxHeap = new MaxBinaryHeap(16);
int[] input = {10, 12, 1, 14, 6, 5, 8, 15, 3, 9, 7, 4, 11, 13, 2};
MaxBinaryHeap maxHeap2 = new MaxBinaryHeap(input);
maxHeap2.printHeap();
for (int x : input)
maxHeap.insert(x);
maxHeap.printHeap();
maxHeap.delete();
maxHeap.printHeap();
System.out.println(Arrays.toString(MaxBinaryHeap.sort(input)));
MaxBinaryHeap small = new MaxBinaryHeap(3);
for (int x = 1; x <= 4; x++)
small.insert(x); // the 4th insertion must be refused
small.printHeap();Expected output:
Heap = 15-14-13-12-9-11-8-10-3-6-7-4-5-1-2-
Heap = 15-14-13-12-9-8-11-10-3-6-7-1-4-5-2-
Heap = 14-12-13-10-9-8-11-2-3-6-7-1-4-5-
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Heap is full, No space to insert new element
Heap = 3-1-2-Task 13 – Lab-exam practice: a min-heap¶
The 1443 lab exam asked for a MinHeap. Copy your class as MinBinaryHeap and change what
is needed so that the root is the minimum: which comparisons change, and which child
does percolate-down follow now? Test with the heap of the slides.
Solution (the two methods that change)
void insert(int x) {
if (isFull()) return;
heap[++heapSize] = x;
int i = heapSize;
while (i / 2 > 0 && x < heap[i / 2]) { // '<' instead of '>'
heap[i] = heap[i / 2];
i = i / 2;
}
heap[i] = x;
}
int delete() { // removes the minimum
int min = heap[1];
heap[1] = heap[heapSize--];
int i = 1, temp = heap[1];
while (2 * i <= heapSize) {
int child = 2 * i;
if (child + 1 <= heapSize && heap[child + 1] < heap[child])
child++; // the SMALLER child
if (heap[child] < temp) {
heap[i] = heap[child];
i = child;
} else break;
}
heap[i] = temp;
return min;
}MinBinaryHeap mh = new MinBinaryHeap(11);
for (int x : new int[]{13, 21, 16, 24, 31, 19, 68, 65, 26, 32})
mh.insert(x);
mh.insert(14);
mh.printHeap();
System.out.println("deleted " + mh.delete());
mh.printHeap();Expected output:
Heap = 13-14-16-24-21-19-68-65-26-32-31-
deleted 13
Heap = 14-21-16-24-31-19-68-65-26-32-Part 2 – Use the JDK¶
Challenge 1 – The largest values¶
Keep a min-heap of the best values seen so far: a new value enters only if it beats the root (the weakest of them). time and memory.
Solution
static List<Integer> topK(int[] a, int k) {
PriorityQueue<Integer> h = new PriorityQueue<>(); // a MIN-heap
for (int x : a) {
if (h.size() < k)
h.offer(x);
else if (x > h.peek()) { // better than the weakest of the best k
h.poll();
h.offer(x);
}
}
List<Integer> res = new ArrayList<>(h);
Collections.sort(res);
return res;
}System.out.println(topK(new int[]{5, 12, 3, 8, 20, 1, 15}, 3));Expected output:
[12, 15, 20]Challenge 2 – Merge sorted lists¶
The next output is always the smallest of the current heads. Keep the heads in a
PriorityQueue<int[]> holding {value, list number, position}, ordered by value.
Solution
static List<Integer> mergeK(List<List<Integer>> lists) {
// heap entries: {value, list number, position in that list}
PriorityQueue<int[]> h = new PriorityQueue<>((x, y) -> x[0] - y[0]);
for (int i = 0; i < lists.size(); i++)
if (!lists.get(i).isEmpty())
h.offer(new int[]{lists.get(i).get(0), i, 0});
List<Integer> out = new ArrayList<>();
while (!h.isEmpty()) {
int[] e = h.poll(); // the smallest head
out.add(e[0]);
List<Integer> src = lists.get(e[1]);
if (e[2] + 1 < src.size()) // its successor enters the heap
h.offer(new int[]{src.get(e[2] + 1), e[1], e[2] + 1});
}
return out;
}System.out.println(mergeK(List.of(List.of(1, 4, 9), List.of(2, 5),
List.of(3, 6, 7))));Expected output:
[1, 2, 3, 4, 5, 6, 7, 9]Challenge 3 – An emergency room¶
Patients are served by severity (highest first); equal severities are served in order of
arrival. Build the order with Comparator.comparingInt(...).reversed().thenComparingInt(...).
(A record is a short way to declare a class whose fields never change.)
Solution
record Patient(String name, int severity, int arrival) {}
static void triage(List<Patient> arrivals) {
PriorityQueue<Patient> er = new PriorityQueue<>(
Comparator.comparingInt(Patient::severity).reversed() // most severe first
.thenComparingInt(Patient::arrival)); // then first come
er.addAll(arrivals);
while (!er.isEmpty()) {
Patient p = er.poll();
System.out.println(p.name() + " (severity " + p.severity() + ")");
}
}triage(List.of(new Patient("Ali", 2, 1), new Patient("Sara", 5, 2),
new Patient("Omar", 3, 3), new Patient("Huda", 5, 4),
new Patient("Nora", 1, 5)));Expected output:
Sara (severity 5)
Huda (severity 5)
Omar (severity 3)
Ali (severity 2)
Nora (severity 1)