Exchange Sort in Java
Learn how Exchange 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
Exchange Sort is one of the simplest comparison sorts. It takes the first position and compares it with every later position, swapping whenever the later value is smaller. After that, the first position holds the smallest value. Then it does the same for the second position, the third, and so on.
Three ideas carry the whole algorithm:
- Fixed position: the outer loop picks a position
iand fills it with the smallest value that is left. - Compare with every later value: the inner loop compares
array[i]with eacharray[j]after it, and swaps them wheneverarray[j]is smaller, so positionikeeps the smallest value seen so far. - Exchange: the name comes from these swaps, which can happen many times for the same position before it settles.
Exchange Sort is often confused with Bubble Sort, because both swap values in two nested loops, but bubble sort only ever compares neighbours. Exchange Sort’s pattern is closer to Selection Sort: both fill position i with the smallest remaining value, but selection sort remembers where that value is and swaps once, while Exchange Sort swaps every time it finds something smaller. It is mostly used as a first sorting algorithm in teaching, because the code is about as short as a sort can be.
This article uses the classic Exchange Sort with two nested loops: position i against every later position j, swapping whenever array[i] > array[j].
Performance Characteristics
Exchange Sort always compares every pair of positions once, so its number of comparisons never changes; only the number of swaps depends on the input.
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 pair is still compared |
| Average | $O(n^2)$ | Random input |
| Worst | $O(n^2)$ | Reverse-sorted input: many swaps on top of the same comparisons |
Why $n^2$? Position 0 is compared with $n - 1$ others, position 1 with $n - 2$, and so on, which adds up to $\frac{n(n - 1)}{2}$ comparisons, 45 for ten values, whatever their order. The swaps vary: on the visualization’s starting data there are 26, where selection sort makes the same 45 comparisons but only 8 swaps.
Exchange Sort has no early exit: a sorted array costs exactly as many comparisons as a shuffled one. Bubble sort with a
swappedflag, or insertion sort, finish a sorted array in $O(n)$, and selection sort makes far fewer swaps; Exchange Sort is the simplest of the four, not the fastest.
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)$: two loop indices |
| In place | Yes |
| Stable | No (a swap can carry a value past an equal value between the two positions) |
Algorithm (Pseudo Code)
Exchange Sort starts with position 0. It compares the value there with the value at position 1, then position 2, and so on to the end of the array. Every time it finds a smaller value, the two swap, so position 0 always holds the smallest value seen so far. When the inner loop reaches the end, position 0 holds the smallest value of the whole array.
The outer loop then moves on to position 1 and repeats the same comparisons with every position after it. Each round fills one more position with the smallest of the remaining values, and when the second-to-last position is done, the last value must be the largest, so the array is sorted.
1
2
3
4
5
6
sort(array):
for i = 0 to n - 2:
for j = i + 1 to n - 1:
if array[i] > array[j]:
swap(i, j)
return array
After round i, the positions 0 .. i hold the i + 1 smallest values in sorted order.
A value that is swapped out of position
ilands at positionj, which may be after other values equal to it. With the values[2a, 2b, 1],2aand1swap, giving[1, 2b, 2a]: the two 2s have changed order, so the sort is not stable.
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 pointers 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
i, the position being filled, and J isj, the later position it is compared with. - Colours: the two values being compared are amber, or salmon when they swap, and the finished positions on the left are green.
- Duplicates: tick Duplicates to sort values between 0 and 3 with repeats. The small number in each cell is its original position, so you can see equal values change order.
- Counters: the footer counts the comparisons and swaps.
Java Code
The implementation is an ExchangeSort class with a single method, sort, made of two nested loops. Two small helpers, swap and greater, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
ExchangeSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
10
11
@Override
public <T extends Comparable<T>> T[] sort(T[] array) {
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1; j < array.length; j++) {
if (SortUtils.greater(array[i], array[j])) {
SortUtils.swap(array, i, j);
}
}
}
return array;
}
sort accepts an array of any Comparable type and sorts it in place. The outer loop walks i from the first position to the second-to-last; the last position needs no round of its own. The inner loop walks j over every position after i, and whenever array[i] is greater than array[j], the two swap, so array[i] always holds the smallest value found so far. Empty and one-element arrays skip the loops entirely, and the array is returned.
Two details are worth noticing:
greateris strict, so equal values are never swapped with each other directly. The sort is still unstable, because a swap between unequal values can jump over an equal one.- The value at
array[i]can change many times in one round. Remembering only the index of the smallest value and swapping once at the end of the round turns this code into selection sort, with the same comparisons and at most $n - 1$ swaps.
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 loops 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 ExchangeSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create an ExchangeSort, pass it an array, and the same array comes back sorted, after 45 comparisons and 26 swaps. The class is package-private, so the code must be in the com.javanibble.sort package.
Summary
- Exchange Sort fills each position in turn by comparing it with every later position and swapping whenever a later value is smaller.
- This implementation uses two nested loops and the
greaterandswaphelpers. - After round
i, positions0 .. ihold the smallest values in sorted order. - It always makes $\frac{n(n - 1)}{2}$ comparisons, $O(n^2)$ in every case, needs $O(1)$ extra space, and is in place but not stable.
- It is a good first sorting algorithm to read. In practice, selection sort does the same with fewer swaps, insertion sort adapts to sorted data, and
Arrays.sort()is much faster.
