Sort using PriorityQueue

A PriorityQueue can be used for sorting a collection:

  • Insert every element from the collection into the PriorityQueue.
  • Remove elements from the PriorityQueue and place them in order, one after another, in the collection.

Exercise Complete the implementation of Heap.sort in the starter code.

private static void sort(Integer[] data) {
  // TODO Implement me
}

Suggestion: Use Java's built-in PriorityQueue.

Solution
private static void sort(Integer[] data) {
  PriorityQueue<Integer> pq = new PriorityQueue<>();
  for (int i = 0; i < data.length; i++) {
    pq.add(data[i]);
  }

  for (int i = 0; i < data.length; i++) {
    data[i] = pq.remove();
  }
}