Sorting with a Priority Queue
The questions in this section use this priority queue interface:
public interface PriorityQueue<T extends Comparable<T>> {
void add(T item); // adds item; throws IllegalArgumentException if item is null
T peek(); // returns the highest-priority item; throws NoSuchElementException if empty
void remove(); // removes the highest-priority item; throws NoSuchElementException if empty
int size(); // returns the number of items
}
ArrayHeap<T> implements PriorityQueue<T> as a binary min-heap stored in an array, so the smallest item has the highest priority. It has a no-argument constructor. Its add and remove are , and its peek is .
Solution
public static void heapSortWithPriorityQueue(int[] arr) {
PriorityQueue<Integer> pq = new ArrayHeap<>();
for (int i = 0; i < arr.length; i++) {
pq.add(arr[i]);
}
for (int i = 0; i < arr.length; i++) {
arr[i] = pq.peek();
pq.remove();
}
}
Solution
- The running time is . The method makes calls to
addand calls toremove, and each call is . - The auxiliary space is . The priority queue holds a copy of all values.
Solution
The priority queue speeds up finding the smallest element that has not been placed yet. Selection sort scans the unsorted part of the array for it, which is per pass.