import java.util.ArrayList; import java.util.Comparator; public class BinaryHeap { protected ArrayList heap; protected Comparator compareFunction = null; public BinaryHeap (Comparator compare Function) { this.compareFunction = compareFunction; } protected int getLeft (int index) { } return 2* (index)+1; protected int getRight (int index) { return 2* (index)+2; } protected int getParent (int index) { } return index>0? (index+1)/2 -1 -1; public void build Heap (ArrayList list) { heap = list; for (int i=(heap.size())/2-1; i >= 0; i--) { heapify(i); } } public int size() { } return heap.size(); public T pop() { if (heap.size() > 0) { } T top heap.get(0); heap.set(0, heap.getLast()); heap.removeLast(); heapify(0); return top; else { return null; } private void heapify(int index) { int L= getLeft (index); int R = getRight (index); int optimal = index; if (Lheap.size() && compareFunction.compare(heap.get(L), heap.get(index)) > 0) { } optimal = L; if (Rheap.size() && compareFunction.compare (heap.get(R), heap.get(optimal)) > 0) { optimal = R; } if (optimal != index) { T tmp heap.get(index); heap.set(index, heap.get(optimal)); heap.set(optimal, tmp); heapify(optimal); } } public void display() { if (heap null) { return; } int current Level = 0; for (int i = 0; i < heap.size(); i++) { int level = (int) (Math. log(i+1)/Math.log(2)); int maxLevels = (int) (Math.log(heap.size())/Math.log(2)); String spacing = ""; for (int j = 0; j < Math.pow(2, maxLevels-level); j++) { spacing += ""; } if (current Level
Part B - Priority Queue
For this part of the assignment, you are to implement a priority queue using the Binary Heap. You will need to create the following:
• insert(...)
• maximum()
• increase key(...)
Feel free to name these functions as you see fit. You are also welcome to create
any other methods that may be helpful in your implementation. Keep in mind,
one way to extend the heap is through inheritance (if useful).
Use the implementation of the priority queue to:
(a) Add items to the list.
(b) Pop off a few items, but not the whole list. The items that were extracted
should be sorted by highest priority.
(c) Add a few items that are low priority.
(d) Add a few items that are high priority.
(e) Pop items off the list and you should see the high priority items show up
before the low priority items.
Here is code below in addition to the BinaryHeap.java (attached):
Step by step
Solved in 2 steps