Post

Priority Queue Sort in Java

Learn how Priority Queue Sort works: its time and space complexity, the algorithm in pseudo code, and a step-by-step visualisation that follows the Java code line by line.

Priority Queue Sort in Java

Introduction

Priority Queue Sort is a comparison sort that lets a data structure do the work. It puts every value into a priority queue, a queue that always hands out its smallest value first, and then takes the values back out one by one. They come out in sorted order.

Three ideas carry the whole algorithm:

  • Priority queue: a collection with two main operations: offer adds a value, and poll removes and returns the smallest value.
  • Binary min-heap: Java’s PriorityQueue stores its values in an array that represents a tree. The children of index p are at 2p + 1 and 2p + 2, and every parent is smaller than or equal to its children, so the smallest value is always at the root, index 0.
  • Sift up and sift down: after an offer, the new value moves up while it is smaller than its parent; after a poll, the last value is moved to the root and moves down while a child is smaller. Both take at most one step per level of the tree.

Priority Queue Sort is heap sort written with a library class. The Heap Sort guide builds the heap inside the array itself; here the heap is a separate PriorityQueue, which makes the code three lines long but needs extra memory. The same pattern, a priority queue that hands out the next smallest item, is behind task schedulers, Dijkstra’s shortest-path algorithm, and merging many sorted streams.

This article uses java.util.PriorityQueue as a min-heap on int values: every value is offered to the queue, and then polled back into the array.

Performance Characteristics

Priority Queue Sort always does the same work, $n$ offers and $n$ polls, so its speed barely depends on the order of the input.

Time Complexity

Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.

CaseTimeWhen it happens
Best$O(n \log n)$Sorted input: each offer stops at once, but every poll still sifts down
Average$O(n \log n)$Random or mixed input
Worst$O(n \log n)$Any input: the heap is always a complete binary tree of depth $\lfloor \log_2 n \rfloor$

Why $n \log n$? The heap is a complete binary tree, so its depth is about $\log_2 n$. An offer sifts up at most one level per step, and a poll sifts down at most one level per step, so each costs $O(\log n)$. There are $n$ of each.

Adding the values one by one builds the heap in $O(n \log n)$. Passing them all at once, as in new PriorityQueue<>(list), uses a bottom-up “heapify” that takes only $O(n)$. The polls still cost $O(n \log n)$, so the total stays the same, but the build gets faster.

Space Complexity

Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.

PropertyValue
Space$O(n)$: the priority queue holds every value, as a boxed Integer
In placeNo (the values pass through the queue, although the result is written back into arr)
StableNo (heap operations don’t keep equal values in order; for int values it can’t be seen)

Algorithm (Pseudo Code)

Priority Queue Sort starts with an empty priority queue and offers it every value of the array. Inside the queue, each new value is put at the end of the heap and then moves up: as long as it is smaller than its parent, the two trade places. When all values are in, the smallest one is at the root.

Then the values are taken out again. Each poll removes the root, the smallest value left, and writes it to the next position of the array. The last value of the heap moves to the empty root and moves down, trading places with its smaller child, until the heap is in order again. When the queue is empty, every value has been written back, smallest first, and the array is sorted.

1
2
3
4
5
6
7
8
sort(arr):
    pq = new PriorityQueue
    for each num in arr:
        pq.offer(num)          // add at the end, sift up
    i = 0
    while pq is not empty:
        arr[i++] = pq.poll()   // take the root, move the last value to the root, sift down
    return arr

After every offer and every poll, each parent in the heap is smaller than or equal to its children, so the root is always the smallest value in the queue.

A min-heap is not a sorted array. Only the root is guaranteed to be the smallest; the rest of the heap is only partly ordered. That partial order is cheap to keep, which is the whole point: the sorting happens one poll at a time.

Visualization

The visualization below follows the Java code line by line, starting with the values 0 to 9 in shuffled order.

Each step shows the array, the heap inside the priority queue, both as a tree and as its internal array, and the line of code that is running, with a short explanation of what just happened. The heap follows the exact steps of Java’s PriorityQueue.

  • Step through: use the arrows to move one step forward or back, or drag the slider to jump to any step.
  • Play: press Play to run the steps automatically, and press it again to pause.
  • Shuffle: press the shuffle button to start again with a new random order.
  • Rows: the top row is arr, and the bottom row is the queue’s internal array. The tree above shows the same heap: index 0 is the root, and the children of index p are at 2p + 1 and 2p + 2.
  • Pointer: I is i, the next position in arr to be written by poll.
  • Colours: the value being offered, and the values being compared, are amber, the values trading places or being written are salmon, and values back in arr in sorted order are green. During the offers, values that are already in the queue fade out in arr.
offered / compared trade places / written sorted in arr I = i

Java Code

The implementation is a PriorityQueueSort utility class: it is final, has a private constructor, and offers one public static method, sort, for int arrays. All the heap work is done by java.util.PriorityQueue, through its offer and poll methods. The class doesn’t use the SortUtils helpers.

The complete code is in the algorithm-examples repository on GitHub: PriorityQueueSort.java.

sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static int[] sort(int[] arr) {
    if (arr == null || arr.length == 0) {
        return arr;
    }

    PriorityQueue<Integer> pq = new PriorityQueue<>();
    for (int num : arr) {
        pq.offer(num);
    }

    int i = 0;
    while (!pq.isEmpty()) {
        arr[i++] = pq.poll();
    }

    return arr;
}

sort returns null and empty arrays straight back. Otherwise it creates an empty PriorityQueue<Integer>, which by default orders its values by their natural order, smallest first. The first loop offers every value, and the second loop polls them back into arr, from index 0 upwards, until the queue is empty. The same array is returned, now sorted.

Two details are worth noticing:

  • The array holds int, but PriorityQueue can only hold objects, so every value is boxed into an Integer on the way in and unboxed on the way out. For large arrays that costs memory and time; Arrays.sort(int[]) avoids it.
  • The Javadoc says the array is sorted “in-place”. The result is written back into arr, but the algorithm needs $O(n)$ extra memory for the queue, so it is not an in-place sort in the usual sense.

offer and poll

offer and poll are methods of java.util.PriorityQueue, so they aren’t in the repository, but they are where the sorting happens:

  • offer(e) puts e in the first free slot of the queue’s internal array, at the bottom of the heap, and sifts it up: while e is smaller than its parent, at index (k - 1) / 2, the parent moves down into e’s slot and e moves up. It stops at the root, or at a parent that is smaller than or equal to it.
  • poll() removes the root, the smallest value, and returns it. It takes the last value of the heap, puts it at the root, and sifts it down: while it is larger than the smaller of its two children, that child moves up and the value moves down.

Both walk one path between the root and the bottom of the tree, so each costs $O(\log n)$ comparisons. The visualization above follows these steps exactly, including which child is chosen and when the sift stops.

Running it

1
2
3
4
int[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
PriorityQueueSort.sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Call the static sort method; numbers itself is sorted, and the same array is also returned. Unlike most of the sorts in this guide, the method takes a plain int[].

Summary

  • Priority Queue Sort is a comparison sort that offers every value to a priority queue and polls them back out, smallest first.
  • This implementation uses java.util.PriorityQueue, a binary min-heap: offer sifts each new value up, and poll removes the root and sifts the last value down.
  • After every operation, each parent in the heap is smaller than or equal to its children, so poll always returns the smallest value left.
  • It runs in $O(n \log n)$ in every case, needs $O(n)$ extra space for the queue, and is not stable.
  • It is the shortest way to write heap sort in Java. For real code, Arrays.sort() is faster and needs no boxing; when memory matters, the Heap Sort guide shows the same idea in place.
This post is licensed under CC BY 4.0 by the author.