/** * @param the Key element. This must implement Comparable. * @param The Value element. This could be anything. * * For methods that exactly follow the interface, see the documentation in * the interface. This implements a priority queue built on top of an * unordered array. * * @author gtowell * Created APRIL 6, 2020 * Modified: */ public class PriorityQueue, V> extends AbstractPriorityQueue { private int getNextt() { if (size==0) return -1; int tmpi = 0; Pair tmp = pqStore[tmpi]; for (int j=1; j[] pqStore; /** THe number of items in the priority queue */ private int size; /** * Initialize the priority queue */ public PriorityQueue() { this(Ordering.MIN); } @SuppressWarnings("unchecked") public PriorityQueue(Ordering order) { this.order=order; pqStore = (Pair[]) new Pair[CAPACITY]; this.size=0; } public int size() { return size; } public boolean isEmpty() { return size==0; } public boolean offer(K newK, V newV) { if (size==CAPACITY) return false; Pair entry = new Pair<>(newK, newV); pqStore[size]=entry; size++; return true; } /** * find and return the index of the next item from the priority queue * @return the next item */ private int getNext() { if (isEmpty()) return -1; // if there are entries, then go through them all to find the next one. // must do this because entries are in no particular order. int lmin = 0; for (int i=1; i curr = pqStore[i]; if (pqStore[lmin].compareTo(curr) > 0) { lmin=i; } } return lmin; } private void remove(int lmin) { for (int i=lmin; i entry = pqStore[0]; pqStore[0]=null; size=0; return entry.theV; } int lmin = getNext(); Pair entry = pqStore[lmin]; remove(lmin); return entry.theV; } public V peek() { int lmin = getNext(); if (lmin<0) return null; Pair entry = pqStore[lmin]; return entry.theV; } public String toString() { StringBuilder sb = new StringBuilder(); for (int i=0; i pq = new PriorityQueue<>(Ordering.ASCENDING); pq.offer(1,"Jane"); pq.offer(10,"WET"); pq.offer(5, "WAS"); System.out.println(pq); System.out.println(pq.poll()); System.out.println(pq); System.out.println(pq.poll()); System.out.println(pq); System.out.println(pq.poll()); System.out.println(pq); System.out.println(); pq = new PriorityQueue<>(Ordering.DESCENDING); pq.offer(1,"Jane"); pq.offer(10,"WET"); pq.offer(5, "WAS"); System.out.println(pq.poll()); System.out.println(pq.poll()); System.out.println(pq.poll()); } }