import java.util.ArrayList; /** * A priority queue using a sorted array list as its backing store. Hence, this implements insertion 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 13, 2020 */ public class PriorityQInsertion, 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 PriorityQInsertion() { this(Ordering.MIN); } public PriorityQInsertion(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); for (int i=0; i< pqStore.size(); i++) { int cmp = pqStore.get(i).doCompare(entry); if (cmp==0) { return false; } if (cmp>0) { // insert before pqStore.add(i, entry); System.out.println(pqStore); return true; } } // add to the end pqStore.add(entry); System.out.println(pqStore); return true; } @Override public V poll() { if (size()==0) return null; Entry entry = pqStore.get(0); pqStore.remove(0); return entry.theV; } @Override public V peek() { if (size()==0) return null; Entry entry = pqStore.get(0); return entry.theV; } public static void main(String[] args) { PriorityQInsertion pq = new PriorityQInsertion(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 PriorityQInsertion<>(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()); } }