Patience Sort in Java
Learn how Patience 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.
Introduction
Patience Sort is a comparison sort inspired by the card game patience (also called solitaire). It deals the values one by one onto piles, following a simple rule, and then merges the piles back together, always taking the smallest card on offer.
Three ideas carry the whole algorithm:
- Dealing rule: a value goes onto the leftmost pile whose top card is not smaller than it; if every top card is smaller, the value starts a new pile on the right.
- Ordered piles: within each pile the cards never increase towards the top, so the top card is the smallest card of its pile. Across the piles, the top cards increase from left to right, which lets a binary search find the right pile.
- Merge with a priority queue: all top cards go into a min-priority queue; repeatedly taking the smallest and replacing it with the next card from the same pile produces the values in sorted order.
Patience Sort is known less as a sort than as a tool: the number of piles it builds is exactly the length of the longest increasing subsequence of the input. That is the standard $O(n \log n)$ way to compute that length, which shows up in interview problems, in diff tools, and in the analysis of card shuffles. As a sort, it is fast on data that already contains long decreasing runs, because those all land on a single pile.
This article uses Patience Sort with binary search and a PriorityQueue merge: Collections.binarySearch finds the pile, and a heap of pile tops performs a $k$-way merge.
Performance Characteristics
Patience Sort’s speed depends on the number of piles it builds: few piles make dealing and merging cheap, many piles make the merge do most of the work.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
In the table, $p$ is the number of piles, at most $n$.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n)$ | A decreasing array: every value lands on the first pile, so $p = 1$ |
| Average | $O(n \log n)$ | Random input: about $2\sqrt{n}$ piles |
| Worst | $O(n \log n)$ | An increasing array: every value starts a new pile, so $p = n$ |
Why $n \log n$? Dealing a value costs a binary search over the $p$ pile tops, $O(\log p)$. Merging takes each value out of the priority queue once, and each queue operation costs $O(\log p)$, because the queue holds one card per pile. With $p \le n$, both phases are $O(n \log p)$, which is at most $O(n \log n)$ and only $O(n)$ when there is a single pile.
An already increasing array is the slowest case: it builds $n$ piles of one card each, and the merge turns into heap sort. If the input is often sorted ascending, reversing it first makes Patience Sort run in linear time.
Space Complexity
Space complexity describes how much extra memory an algorithm needs, beyond the input itself, as the input gets larger.
| Property | Value |
|---|---|
| Space | $O(n)$: the piles hold every value, plus the list of top cards and the queue |
| In place | No (the values are dealt into piles and merged back) |
| Stable | No (the priority queue doesn’t keep equal values in their original order) |
Algorithm (Pseudo Code)
Patience Sort starts with no piles. It takes the values one at a time and looks at the top card of every pile, from left to right. The value is put on the first pile whose top card is not smaller than it. If there is no such pile, the value starts a new pile on the right. Because the top cards are always in increasing order from left to right, the right pile can be found with a binary search instead of checking every pile.
When all values have been dealt, every pile’s top card is its smallest card. The top cards go into a priority queue. The queue hands out the smallest of them, which is the smallest value overall; it is written to the array, and the next card of the same pile takes its place in the queue. This repeats until every pile is empty, and the values come out in sorted order.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
sort(array):
piles = formPiles(array)
pq = mergePiles(piles)
extractPiles(array, pq)
formPiles(array):
piles = [], lastElements = [] // lastElements[i] is the top card of pile i
for each x in array:
pos = first index with lastElements[pos] >= x (binary search)
if pos < number of piles: piles[pos].add(x), lastElements[pos] = x
else: start a new pile with x, lastElements.add(x)
return piles
mergePiles(piles):
pq = new PriorityQueue
for each pile: pq.add((pile.removeLast(), pile))
return pq
extractPiles(array, pq):
index = 0
while pq is not empty:
node = pq.poll()
array[index++] = node.value
if node.pile is not empty: pq.add((node.pile.removeLast(), node.pile))
After the dealing phase, the top cards increase from left to right and every pile decreases from bottom to top, so the queue always holds the smallest remaining card of each pile.
A card only goes on a pile whose top is at least as large, so every pile is a decreasing sequence. Any increasing subsequence of the input can use at most one card from each pile, which is why it can’t be longer than the number of piles; the dealing rule makes sure one that long always exists.
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 piles, the priority queue during the merge, and the line of code that is running, with a short explanation of what just happened:
- 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.
- Piles: each column is a pile, dealt from top to bottom like cards in patience; the lowest card shown in a column is the pile’s top card, the one at the end of its list.
- Queue: during the merge, the queue row shows the cards waiting in the priority queue, smallest first.
- Colours: the value being dealt, or the smallest card in the queue, is amber; a card just placed or just added to the queue is salmon; and values written back to the array are green.
- Piles count: the footer shows the number of piles, which is also the length of the longest increasing subsequence of the input.
Java Code
The implementation is a PatienceSort class with one public method, sort, and three private methods: formPiles deals the values onto piles, mergePiles puts the top card of each pile into a priority queue, and extractPiles merges the piles back into the array. A small private record, PileNode, pairs a value with the pile it came from. The class doesn’t use the SortUtils helpers.
The complete code is in the algorithm-examples repository on GitHub:
PatienceSort.java.
sort
1
2
3
4
5
6
7
8
9
10
11
12
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array.length == 0) {
return array;
}
final List<List<T>> piles = formPiles(array);
final PriorityQueue<PileNode<T>> pq = mergePiles(piles);
extractPiles(array, pq);
return array;
}
sort is the entry point. It accepts an array of any Comparable type and returns an empty array straight back. Otherwise it deals the values onto piles, builds the priority queue from the pile tops, and lets extractPiles write the merged values back into the array, which is returned, sorted.
formPiles
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private static <T extends Comparable<T>> List<List<T>> formPiles(final T[] array) {
final List<List<T>> piles = new ArrayList<>();
final List<T> lastElements = new ArrayList<>();
for (T x : array) {
int pos = Collections.binarySearch(lastElements, x);
if (pos < 0) {
pos = -pos - 1;
}
if (pos < piles.size()) {
piles.get(pos).add(x);
lastElements.set(pos, x);
} else {
List<T> newPile = new ArrayList<>();
newPile.add(x);
piles.add(newPile);
lastElements.add(x);
}
}
return piles;
}
formPiles keeps two lists: piles, one list per pile with its top card at the end, and lastElements, the top card of each pile, in increasing order. Collections.binarySearch looks for x among the tops. When it finds an equal top, it returns that index; when it doesn’t, it returns -(insertion point) - 1, and -pos - 1 turns that back into the index of the first top larger than x. Either way, pos is the leftmost pile whose top is not smaller than x. If such a pile exists, x goes on it and becomes its new top; otherwise x starts a new pile.
Two details are worth noticing:
- The tops stay strictly increasing from left to right: a new pile is only started by a value larger than every top, and placing
xon pileposreplaces a top that was at leastxwithxitself, which is still larger than the top to its left. That’s what makes the binary search valid, even with duplicates. - The Javadoc says each element in a pile is “smaller than the one before it”. With duplicates, equal values can be stacked on each other, so “not larger” is the precise rule.
mergePiles
1
2
3
4
5
6
7
private static <T extends Comparable<T>> PriorityQueue<PileNode<T>> mergePiles(final Iterable<List<T>> piles) {
PriorityQueue<PileNode<T>> pq = new PriorityQueue<>();
for (List<T> pile : piles) {
pq.add(new PileNode<>(pile.removeLast(), pile));
}
return pq;
}
Despite its name, mergePiles only prepares the merge: it removes the top card of every pile and adds it to a priority queue, wrapped in a PileNode that remembers which pile it came from. The queue now holds the smallest card of every pile.
List.removeLast()was added in Java 21, as part of sequenced collections. On older Java versions this class doesn’t compile;pile.remove(pile.size() - 1)does the same and works everywhere.
extractPiles
1
2
3
4
5
6
7
8
9
10
private static <T extends Comparable<T>> void extractPiles(final T[] array, final PriorityQueue<PileNode<T>> pq) {
int index = 0;
while (!pq.isEmpty()) {
PileNode<T> node = pq.poll();
array[index++] = node.value;
if (!node.pile.isEmpty()) {
pq.add(new PileNode<>(node.pile.removeLast(), node.pile));
}
}
}
extractPiles performs a $k$-way merge. It repeatedly polls the smallest card from the queue and writes it to the next position of the array. If that card’s pile still has cards, the pile’s new top, its next-smallest card, joins the queue. Since the queue always holds the smallest remaining card of every non-empty pile, the card it hands out is always the smallest value left.
PileNode
1
2
3
4
5
6
private record PileNode<T extends Comparable<T>>(T value, List<T> pile) implements Comparable<PileNode<T>> {
@Override
public int compareTo(PileNode<T> other) {
return this.value.compareTo(other.value);
}
}
PileNode is a small record that holds a value and a reference to the pile it was taken from, so extractPiles knows where to get the replacement card. It compares by value only, which is all the priority queue needs; ties between equal values from different piles are broken arbitrarily by the heap.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new PatienceSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a PatienceSort, pass it an array, and the same array comes back sorted. For this input the values are dealt onto 3 piles, and the longest increasing subsequence, for example 2, 4, 6, also has length 3.
Summary
- Patience Sort is a comparison sort that deals values onto piles like the card game, then merges the piles with a priority queue.
- This implementation finds each value’s pile with
Collections.binarySearchon the pile tops and performs a $k$-way merge with aPriorityQueueofPileNodes. - Every pile decreases towards its top and the tops increase across the piles, so the queue always holds each pile’s smallest card; the number of piles equals the length of the longest increasing subsequence.
- It runs in $O(n \log n)$ in general and $O(n)$ when the input is decreasing, needs $O(n)$ extra space, and is not stable and not in place.
- Use it when you also need the longest increasing subsequence, or for data with long decreasing runs. To just sort,
Arrays.sort()is simpler and usually faster. The class requires Java 21 or later.
