Circle Sort in Java
Learn how Circle 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
Circle Sort is a recursive comparison sort that compares values in circles. It takes a range, compares its first value with its last, the second with the second-to-last, and so on towards the middle, swapping any pair that is out of order, like folding the range in half. Then it does the same for both halves, recursively. Whole passes repeat until one pass makes no swap.
Three ideas carry the whole algorithm:
- Outside-in pairs: in each range,
lowstarts at the left end andhighat the right end; they move towards each other, and every pair with the larger value on the left is swapped. Drawn as arcs, the pairs form concentric circles. - Recursion on halves: after its own pairs, each range is split in the middle and both halves get the same treatment, down to single values.
- Repeat until quiet: one pass doesn’t always sort everything, so the whole procedure runs again until a pass makes no swap at all.
Circle Sort is a little-known algorithm, best known from programming-puzzle collections such as Rosetta Code, and it has stayed a curiosity: it is short, recursive, and does well on nearly sorted data, but it is neither stable nor faster than the classic $O(n \log n)$ sorts. Its comparison pattern resembles a sorting network, a relative of Bitonic Sort, which compares fixed pairs whatever the data.
This article uses recursive Circle Sort with passes repeated until nothing is swapped, including the special comparison of the middle value in ranges of odd length.
Performance Characteristics
One pass of Circle Sort has a fixed cost; how fast the whole sort runs depends on how many passes the data needs.
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 \log n)$ | An already sorted array: one pass, which only confirms there is nothing to swap |
| Average | about $O(n \log^2 n)$ | Random input: a number of passes that grows slowly with $n$ |
| Worst | not known exactly | No tight bound has been proven; the number of passes is the open question |
Why $n \log n$ per pass? A pass compares about $n / 2$ pairs on every level of the recursion, and there are $\log_2 n$ levels, so one pass costs about $\frac{n}{2} \log_2 n$ comparisons. With the repository code, a sorted array of 100,000 values costs exactly one pass, 853,904 comparisons, and a reverse-sorted array two, because the first pass reverses it completely and the second confirms the result. Random input needed about 10.8 $n \log_2 n$ comparisons for 100,000 values, against 5.6 for 1,000, so the number of passes grows slowly with $n$.
Circle Sort’s last pass is always a check that changes nothing. On data that is already sorted, that check is the whole cost, which is why sorted input is fast: $O(n \log n)$ for one pass.
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(\log n)$ for the recursion stack |
| In place | Yes |
| Stable | No (pairs far apart are swapped past equal values between them) |
Algorithm (Pseudo Code)
Circle Sort looks at the whole array. It compares the first value with the last, the second with the second-to-last, and so on, moving both ends towards the middle, and swaps each pair whose left value is larger. If the range has an odd length, the pointers meet on the middle value, which is compared with its right neighbour. Then the range is split in half, and both halves are handled the same way, recursively, until the ranges hold a single value.
That is one pass. Each pass moves large values to the right and small values to the left over long distances, but it doesn’t guarantee a sorted array. So the pass is repeated, and every pass reports whether it swapped anything. When a whole pass makes no swap, every compared pair is in order, and the array is sorted.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
sort(array):
while doSort(array, 0, n - 1):
// repeat until a pass makes no swap
doSort(array, left, right):
if left == right: return false
swapped = false
low = left, high = right
while low < high:
if array[low] > array[high]: swap(low, high), swapped = true
low++, high--
if low == high and array[low] > array[high + 1]:
swap(low, high + 1), swapped = true
mid = left + (right - left) / 2
leftSwapped = doSort(array, left, mid)
rightSwapped = doSort(array, mid + 1, right)
return swapped or leftSwapped or rightSwapped
When a pass makes no swap, every pair it compares is in order, including every pair of neighbours at the bottom of the recursion, so the array is sorted.
The extra comparison
array[low] > array[high + 1]only happens when the range has an odd length. The two pointers then meet on the middle value, which has no partner of its own, so it is compared with its right neighbour instead.
Visualization
The visualization below follows the Java code call by call, starting with the values 0 to 9 in shuffled order.
Each step shows one call of doSort: its range, the pairs it compares, drawn as arcs from the outside in, and the line of code that ran, with a short explanation of what 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.
- Range and arcs: values outside the range of the call fade out. Each arc joins a compared pair; the gray bar marks where the range is split for the recursion.
- Colours: pairs that were already in order are amber, pairs that were swapped are salmon, and the array turns green when a pass makes no swap.
- Passes: the footer shows the pass number and the number of comparisons; a step at the end of each pass says whether another pass is needed.
Java Code
The implementation is a CircleSort class with one public method, sort, which repeats passes, and one private method, doSort, which performs one pass over a range, recursively. Two small helpers, swap and greater, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
CircleSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
if (array.length == 0) {
return array;
}
while (doSort(array, 0, array.length - 1)) {
}
return array;
}
sort returns an empty array straight back. Otherwise it calls doSort on the whole array again and again, as long as the pass reports a swap. The while loop has an empty body: all the work happens in the condition. When a pass returns false, the array is sorted in place and returned.
doSort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
private <T extends Comparable<T>> boolean doSort(final T[] array, final int left, final int right) {
boolean swapped = false;
if (left == right) {
return false;
}
int low = left;
int high = right;
while (low < high) {
if (SortUtils.greater(array[low], array[high])) {
SortUtils.swap(array, low, high);
swapped = true;
}
low++;
high--;
}
if (low == high && SortUtils.greater(array[low], array[high + 1])) {
SortUtils.swap(array, low, high + 1);
swapped = true;
}
final int mid = left + (right - left) / 2;
final boolean leftHalfSwapped = doSort(array, left, mid);
final boolean rightHalfSwapped = doSort(array, mid + 1, right);
return swapped || leftHalfSwapped || rightHalfSwapped;
}
doSort handles array[left .. right]. A single value can’t be out of order, so it returns false. Otherwise low and high walk in from both ends, and every pair whose left value is larger is swapped. When the range has an odd length, the loop ends with low == high on the middle value, which is then compared with its right neighbour at high + 1; that index is always inside the range, because high stopped before right. The range is split at mid, both halves are handled recursively, and the method reports whether anything in the whole range was swapped.
Two details are worth noticing:
- Both recursive calls are made before their results are combined. Writing
return swapped || doSort(left half) || doSort(right half)would skip the right half whenever the left half swapped, because||stops at the firsttrue. - The recursion splits ranges exactly in half, so a pass goes $\log_2 n$ levels deep, and the stack stays $O(\log n)$.
swap and greater
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 greater(T firstElement, T secondElement) {
return firstElement.compareTo(secondElement) > 0;
}
These helpers from SortUtils keep the pass easy to read. swap exchanges two elements, and greater returns true when the first element is larger 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 CircleSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a CircleSort, pass it an array, and the same array comes back sorted, after four passes and 76 comparisons. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Circle Sort compares the ends of a range inwards, swapping out-of-order pairs, then does the same for both halves, recursively.
- This implementation repeats full passes until one reports no swap, and compares the middle value of an odd-length range with its right neighbour.
- A pass without any swap proves every compared pair is in order, including all neighbouring pairs, so the array is sorted.
- It costs $O(n \log n)$ per pass, runs in one pass on sorted input and about $O(n \log^2 n)$ on random input, needs $O(\log n)$ stack space, and is in place but not stable.
- It is a neat recursive puzzle more than a practical sort; for real data, use
Arrays.sort().
