import java.util.ArrayList; /** * A priority queue using an unordered arraylist at the back. Hence, the equivalent of selection sort. * * @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. * * @author gtowell * Created APRIL 6, 2020 * Modified: April 13, 2020 */ public class PriorityQSelection, V> extends AbstractPriorityQueue { /** The thing actually holding the data in the priority queue. Using an ArrayList * to get unbounded length. */ final private ArrayList> pqStore; /** * Initialize the priority queue */ public PriorityQSelection() { this(Ordering.MIN); } public PriorityQSelection(Ordering order) { this.order=order; pqStore = new ArrayList<>(); } @Override public int size() { return pqStore.size(); } @Override public boolean isEmpty() { return pqStore.isEmpty(); } @Override public boolean offer(K newK, V newV) { Entry entry = new Entry<>(newK, newV); pqStore.add(entry); // Note that this always succeeds, so always return true. return true; } /** * find and return the next item from the priority queue * @return the next item */ private Entry getNext() { if (isEmpty()) return null; // if there are entries, then go through them all to find the next one. // must do this because entries are in no particular order. Entry cmin = pqStore.get(0); // see with the item in position 0 // the start doing comparisons with item in position 1. for (int i=1; i curr = pqStore.get(i); int cmp = pqStore.get(i).doCompare(cmin); if (cmp<0) { cmin=curr; } } pqStore.remove(cmin); return cmin; } @Override public V poll() { Entry entry = getNext(); if (entry==null) return null; pqStore.remove(entry); return entry.theV; } @Override public V peek() { Entry entry = getNext(); if (entry==null) return null; return entry.theV; } public static void main(String[] args) { PriorityQSelection pq = new PriorityQSelection(Ordering.MIN); 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()); System.out.println(); pq = new PriorityQSelection<>(Ordering.MAX); 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()); } }