package ap;
import java.util.ArrayList;
import java.util.List;
/**
* A simple yet completely functional implementation
* of the PriorityQueue interface. The interface
* is part of the AP subset and is testable. This implementation
* is not part of the subset, but is useful in
* a classroom setting.
*
* This class supports (n = # items stored in priority queue)
* PriorityQueue operations with the following
* complexities.
*
*
| operation | worst case | average case |
|---|---|---|
| add | O(1) | O(1) |
| peekMin | O(n) | O(n) |
| removeMin | O(n) | O(n) |
* The underlying storage is java.util.ArrayList which
* supports constant time add (to end), but which requires linear
* search to find the smallest element.
*
* This implementation is provided * at apcentral. */ public class ArrayPriorityQueue implements PriorityQueue { /** * Constructs an initially empty priority queue. */ public ArrayPriorityQueue() { items = new ArrayList(); } public void add(Object x) { items.add(x); } public Object removeMin() { Object min = peekMin(); items.remove(min); return min; } public Object peekMin() { int minIndex = 0; for (int i = 1; i < items.size(); i++) { Comparable c = (Comparable) items.get(i); if (c.compareTo(items.get(minIndex)) < 0) { minIndex = i; } } return items.get(minIndex); } public boolean isEmpty() { return items.size() == 0; } private List items; }