Swap Sort in Java
Learn how Swap 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
Swap Sort is a comparison sort that places a value by counting. For the value at the current position, it counts how many values after it are smaller: that count says exactly how far to the right the value belongs. The value is swapped straight to that spot, and the value that comes back is counted next. Only when the current value is already in its place does the position move on.
Three ideas carry the whole algorithm:
- Count to find the place: if
kvalues afterindexare smaller thanarray[index], its final position isindex + k. - Swap and recount: after the swap, a new value sits at
index, so the count starts again for that value; the position only moves on when the count is 0. - Skip equal values: if the target slot already holds an equal value, the target moves one further, so that two equal values don’t keep swapping with each other.
Swap Sort is closely related to Cycle Sort: both find a value’s final position by counting smaller values, and every swap puts one value in its final place. Cycle Sort carries the displaced value around the cycle and writes each value once; Swap Sort simply swaps and starts counting again, which makes it shorter to write but costs more comparisons.
This article uses Swap Sort with an equal-value skip, so that it works for arrays with duplicates as well as for distinct values.
Performance Characteristics
Swap Sort recounts from scratch after every swap, so its comparisons are always quadratic; only the number of swaps depends on how the values are arranged.
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^2)$ | An already sorted array: no swaps, but every position is still counted once |
| Average | $O(n^2)$ | Random input: about $1.5n^2$ comparisons with the repository code |
| Worst | $O(n^2)$ | Any input: at most $n - 1$ swaps, and each one is followed by a count of up to $n$ |
Why $n^2$? Every count looks at all the values after index, which is up to $n$ comparisons. There is one count for each position the loop moves past, $n - 1$ of them, plus one more after every swap, and since every swap puts a value in its final place, there are at most $n - 1$ swaps. That makes at most about $2n$ counts of up to $n$ comparisons each. With the repository code, 4,000 sorted values take 0.5 $n^2$ comparisons and 4,000 random values about 1.5 $n^2$.
Swap Sort makes at most $n - 1$ swaps, like Cycle Sort and Selection Sort, but it pays for every one with a full recount. When swaps are cheap, insertion sort makes fewer comparisons; when writes are expensive, Cycle Sort makes fewer writes.
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(1)$: a position, a target and a counter |
| In place | Yes |
| Stable | No (a value is swapped straight past others, including equal values) |
Algorithm (Pseudo Code)
Swap Sort starts at index 0. It counts the values after index 0 that are smaller than the value there. If the count is 0, nothing smaller comes after it, so the value is already in its final place, and the index moves on. Otherwise the value belongs exactly that many places further right, so it is swapped there, and the value that came back to index 0 is counted next.
If the target slot already holds a value equal to the one being placed, the target moves right past it, and past any further equal values, before swapping. Every swap puts one value into its final position, and every move of the index confirms another, so when the index reaches the last position, the whole array is sorted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
sort(array):
index = 0
while index < n - 1:
count = number of values after index that are smaller than array[index]
if count > 0:
target = index + count
while array[target] == array[index]: target++
swap(index, target)
else:
index++
return array
getSmallerElementCount(array, index):
count the values in array[index + 1 .. n - 1] that are smaller than array[index]
Every value before index is in its final place, and every swap puts one more value in its final place.
Without the equal-value skip, two equal values could chase each other: both count the same number of smaller values, so each one would send the other back to the slot it came from, forever. The
whileloop moves the target past the equal values that already sit where this value would go.
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 current position and target, the values being counted, 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.
- Pointers: I is
index, the position being settled (also outlined), and T istarget, where its value belongs. - Colours: the smaller values that were counted are amber, the two values being swapped are salmon, and values in their final place are green.
- Duplicates: tick Duplicates to sort values between 0 and 3 with repeats, and watch the target skip over equal values. The small number in each cell is its original position.
- Counters: the footer counts the comparisons and swaps.
Java Code
The implementation is a SwapSort class with one public method, sort, and one private method, getSmallerElementCount, which counts the smaller values after a position. Two small helpers, swap and less, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
SwapSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
int index = 0;
while (index < array.length - 1) {
final int amountSmallerElements = this.getSmallerElementCount(array, index);
if (amountSmallerElements > 0) {
int target = index + amountSmallerElements;
while (array[target].compareTo(array[index]) == 0) {
target++;
}
SortUtils.swap(array, index, target);
} else {
index++;
}
}
return array;
}
sort accepts an array of any Comparable type and sorts it in place. The while loop settles one position at a time. When values after index are smaller, the value belongs at index + amountSmallerElements; the inner loop moves the target past any equal values already sitting there, and the swap puts the value in its final place. The loop then runs again for the same index, with the value that came back. When no smaller value is left, index moves on. Empty and one-element arrays skip the loop.
Two details are worth noticing:
- The inner
whilecan’t run off the end of the array. The values equal toarray[index]belong in a block of slots that starts atindex + amountSmallerElements, andarray[index]itself isn’t in that block yet, so at least one slot in the block holds a different value. indexonly moves when the current value is in place, so a position can take several rounds of counting and swapping before the loop moves on.
getSmallerElementCount
1
2
3
4
5
6
7
8
9
10
private <T extends Comparable<T>> int getSmallerElementCount(final T[] array, final int index) {
int counter = 0;
for (int i = index + 1; i < array.length; i++) {
if (SortUtils.less(array[i], array[index])) {
counter++;
}
}
return counter;
}
getSmallerElementCount walks every value after index and counts those that are strictly smaller than array[index]. The values before index are already in their final places and all smaller or equal, so they don’t need counting: the count alone is the distance to the value’s final position. This scan is where nearly all of the sort’s comparisons happen.
swap and less
1
2
3
4
5
6
7
8
9
10
11
public static <T> void swap(T[] array, int i, int j) {
if (i != j) {
final T temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) < 0;
}
These helpers from SortUtils keep the code easy to read. swap exchanges two elements, and less returns true when the first element is smaller than the second, using compareTo, so the algorithm works for any type that implements Comparable.
Running it
1
2
3
4
Integer[] numbers = {7, 2, 9, 4, 0, 8, 3, 6, 1, 5};
new SwapSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a SwapSort, pass it an array, and the same array comes back sorted, after 121 comparisons and 8 swaps. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Swap Sort places each value by counting the smaller values after it, which gives its final position directly, and swapping it there.
- This implementation recounts for the value that comes back after every swap, and skips equal values at the target so that duplicates don’t swap forever.
- Every value before
indexis in its final place, and every swap adds one more. - It always makes $O(n^2)$ comparisons but at most $n - 1$ swaps, needs $O(1)$ extra space, and is in place but not stable.
- It is a compact way to show sorting by counting. Cycle Sort does the same with fewer writes, and
Arrays.sort()is far faster.
