Strand Sort in Java
Learn how Strand 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
Strand Sort is a comparison sort that pulls sorted strands out of a list and merges them. Each pass walks through the values that are left, keeps every value that is not smaller than the last one it kept, and so pulls out one increasing sequence. That strand is merged into the result, and the passes repeat until the list is empty.
Three ideas carry the whole algorithm:
- Strand: an increasing sequence taken from the list in one pass, greedily: the first value, then every later value that is at least as large as the strand’s end.
- Removal: the values of a strand are removed from the list, so each pass only looks at what earlier strands left behind.
- Merge: every strand is already sorted, so it can be merged into the sorted result in linear time, exactly like the merge step of Merge Sort.
Strand Sort works best on data that already contains long increasing runs: then a few strands cover everything, and a fully sorted list is a single strand. It is naturally suited to linked lists, where removing a value from the middle is cheap, and it is mainly known as a simple illustration of how merging sorted runs can sort a list.
This article uses Strand Sort on an ArrayList, with a merge that takes the value from the earlier result first on ties, which keeps the sort stable.
Performance Characteristics
Strand Sort’s speed depends on the number of strands: every pass scans the remaining list, and every strand costs a merge with the growing result.
Time Complexity
Time complexity describes how the number of steps an algorithm takes grows as the input gets larger.
| Case | Time | When it happens |
|---|---|---|
| Best | $O(n)$ | An already sorted list: one strand (on a linked list; this ArrayList version is slower, see below) |
| Average | $O(n^2)$ | Random input: about $2\sqrt{n}$ strands, each costing a scan and a merge |
| Worst | $O(n^2)$ | A reverse-sorted list: every value is its own strand |
Why $n^2$? With $s$ strands, the passes scan the remaining list $s$ times, and the merges copy the growing result $s$ times, which is $O(s \cdot n)$ in total. On reverse-sorted input, $s = n$. On random input the strands get shorter as the list runs down, which gives about $2\sqrt{n}$ strands, still too many for $n \log n$.
Removing a value from the middle of an
ArrayListshifts every value after it, so this implementation pays $O(n)$ per removal even on sorted input. With the repository code, 30,000 sorted values take about 21 ms and 100,000 take about 314 ms, about 15 times as long for 3.3 times the data. On aLinkedListwith an iterator, each removal is $O(1)$, and sorted input really is linear.
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 working list, the current strand, and a new result list for every merge |
| In place | No (the values move between lists and are copied back at the end) |
| Stable | Yes (equal values join strands in order, and the merge takes the earlier strand first) |
Algorithm (Pseudo Code)
Strand Sort starts with a copy of the array as a list and an empty result. Each pass starts a new strand with the first value left in the list and removes it. Then it walks through the rest of the list: a value that is not smaller than the strand’s current end is removed and added to the strand, and a smaller value is skipped and stays for a later pass. At the end of the pass, the strand is an increasing sequence.
The strand is merged into the result: at every step the smaller of the two front values is taken, so the result stays sorted. The passes repeat until the list is empty. Every value has then been in exactly one strand and merged into the result, so the result is the sorted array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
sort(array):
list = array as a list
result = empty
while list is not empty:
strand = [list.removeFirst()]
i = 0
while i < list.size():
if strand.last <= list[i]: strand.add(list.remove(i))
else: i++
result = merge(result, strand)
copy result into array
merge(left, right):
repeatedly take the smaller front value, left first on ties
then append whatever is left of either list
After each pass, the result holds every value removed so far, in sorted order.
When a value is removed from the list,
iis not increased: the next value has just moved into positioni. Only skipping a value movesiforward. Getting this wrong skips every value right after a removed one.
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 values left in the list, the strand being built, the merged result 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.
- Rows: the top row is the list of values not yet in any strand, the middle row is the current strand, and the bottom row is the sorted result.
- Pointer: I is
i, the position in the list being checked. - Colours: a value checked and skipped is amber, the value just added to the strand is salmon, the rest of the strand is amber, and the result is green.
- Strands: the footer counts the strands. Sorted input needs one; reversed input needs one per value.
Java Code
The implementation is a StrandSort class with one public method, sort, and two private static methods: strandSort pulls out the strands, and merge merges a strand into the result. The class doesn’t use the SortUtils helpers.
The complete code is in the algorithm-examples repository on GitHub:
StrandSort.java.
sort
1
2
3
4
5
6
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
List<T> unsortedList = new ArrayList<>(Arrays.asList(array));
List<T> sortedList = strandSort(unsortedList);
return sortedList.toArray(array);
}
sort copies the array into a new ArrayList, because Arrays.asList alone returns a fixed-size list that doesn’t support remove. It sorts the list with strandSort and copies the result back with toArray(array): since the list has exactly as many values as the array, toArray writes into the array that was passed in and returns it, so the caller’s array ends up sorted.
strandSort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private static <T extends Comparable<? super T>> List<T> strandSort(List<T> list) {
if (list.size() <= 1) {
return list;
}
List<T> result = new ArrayList<>();
while (!list.isEmpty()) {
final List<T> sorted = new ArrayList<>();
sorted.add(list.removeFirst());
for (int i = 0; i < list.size();) {
if (sorted.getLast().compareTo(list.get(i)) <= 0) {
sorted.add(list.remove(i));
} else {
i++;
}
}
result = merge(result, sorted);
}
return result;
}
strandSort returns lists of zero or one value straight back. Otherwise it repeats passes until the list is empty. Each pass starts a strand, called sorted, with the first value of the list, then walks the list with i. A value that is not smaller than the strand’s last value is removed and appended; i stays where it is, because the next value has moved into its place. A smaller value is skipped with i++. At the end of the pass, the strand is merged into result.
Two details are worth noticing:
- The
forloop has no update part:ionly moves when a value is skipped, which is what makes removing during the loop safe. - The comparison is
<= 0, so an equal value joins the strand. That keeps equal values in their original order within a strand, which is half of what makes the sort stable.
List.removeFirst()andList.getLast()were added in Java 21, as part of sequenced collections, so this class doesn’t compile on older Java versions.list.remove(0)andsorted.get(sorted.size() - 1)do the same and work everywhere.
merge
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private static <T extends Comparable<? super T>> List<T> merge(List<T> left, List<T> right) {
List<T> result = new ArrayList<>();
int i = 0;
int j = 0;
while (i < left.size() && j < right.size()) {
if (left.get(i).compareTo(right.get(j)) <= 0) {
result.add(left.get(i));
i++;
} else {
result.add(right.get(j));
j++;
}
}
result.addAll(left.subList(i, left.size()));
result.addAll(right.subList(j, right.size()));
return result;
}
merge is the standard merge of two sorted lists into a new one: it repeatedly takes the smaller front value, and when one list runs out, appends the rest of the other. On a tie, <= 0 takes the value from left, the earlier result, first. A later strand never contains a value that came before an equal value in an earlier strand, so equal values keep their original order, and the sort is stable.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new StrandSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a StrandSort, pass it an array, and the same array comes back sorted, after four strands. The array holds Integer, not int, because the method works with Comparable objects, and the class needs Java 21 or later.
Summary
- Strand Sort is a comparison sort that repeatedly pulls an increasing strand out of the list and merges it into the sorted result.
- This implementation builds each strand greedily in one pass over an
ArrayList, removing the values it takes, and merges with a stable, left-first merge. - After each pass, the result holds every value taken so far, in sorted order; when the list is empty, it holds them all.
- It runs in $O(n)$ on sorted input with a linked list but $O(n^2)$ in general, needs $O(n)$ extra space, and is stable but not in place. This class requires Java 21.
- Use it on linked lists with long sorted runs. For general data, Merge Sort uses the same merge with a guaranteed $O(n \log n)$, and
Arrays.sort()is faster still.
