Gnome Sort in Java
Learn how Gnome 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
Gnome Sort is a simple comparison sort, usually explained with a garden gnome sorting a row of flower pots. The gnome looks at the pot in front of it and the one before it. If they are in order, it steps forward; if not, it swaps them and steps back. When it walks off the end of the row, the pots are sorted.
Three ideas carry the whole algorithm:
- One position, one pair: the gnome stands at index
iand compares the pair(i - 1, i). - Swap and step back: when the pair is out of order, it swaps and moves one step back, so the smaller value keeps travelling left until it reaches its place. This is exactly how insertion sort moves a value, but done with swaps.
- Jump forward: the optimised version remembers, in
j, where it was before walking back. Once the value is in place, the gnome jumps straight back there instead of walking over the values it has just passed.
Hamid Sarbazi-Azad described the algorithm in 2000 as “stupid sort”, and Dick Grune renamed it after the Dutch garden gnome. It needs a single loop and no nested loop, which makes it one of the shortest sorting algorithms to write. With the jump, it makes the same moves as Insertion Sort, only with swaps instead of shifts.
This article uses the optimised Gnome Sort with a remembered position j, so that after walking a value back, the gnome jumps forward instead of walking.
Performance Characteristics
Like insertion sort, Gnome Sort’s work depends on how far each value has to travel left, so it is fast on nearly sorted data and slow on reversed data.
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 array of distinct values: the gnome walks straight to the end |
| Average | $O(n^2)$ | Random input |
| Worst | $O(n^2)$ | A reverse-sorted array, and, in this code, an array of equal values (see below) |
Why $n^2$? Every swap moves one value one position left, and on random data the values have to travel about $n^2 / 4$ positions in total. The jump only saves the walk forward again; it doesn’t reduce the swaps. Without the jump, the plain version also walks back over the same values, which adds another $O(n^2)$ comparisons.
Because it swaps neighbours instead of shifting a block of values and writing the key once, Gnome Sort makes about three times as many writes as insertion sort for the same moves. When simplicity isn’t the goal, insertion sort is the better choice.
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 indices |
| In place | Yes |
| Stable | Not in this code (equal neighbours are swapped); yes with a non-strict comparison (see below) |
Algorithm (Pseudo Code)
The gnome starts at index 1, looking at the first two values. If the value before it is smaller, the pair is in order, and the gnome moves on. If not, the two values swap and the gnome steps back one position, so it now looks at the value that was just moved and the one before it. It keeps swapping and stepping back until that value meets a smaller one, or reaches the front of the array.
At that point the value is in its place, and everything up to the furthest position the gnome had reached is sorted. Instead of walking forward over those values again, the gnome jumps straight to the next position it hasn’t visited, which it remembered in j. When the gnome steps past the last index, the whole array is sorted.
1
2
3
4
5
6
7
8
9
10
sort(array):
i = 1, j = 2
while i < n:
if array[i - 1] < array[i]:
i = j++ // in order: jump to the next unvisited position
else:
swap(i - 1, i)
i = i - 1 // step back with the value
if i == 0: i = j++ // reached the front: jump forward
return array
Whenever the gnome jumps forward with i = j++, the values it has visited, array[0 .. j - 1] before the jump, are sorted. While it walks back, everything except the value it carries is in order.
The test
array[i - 1] < array[i]is strict. Two equal neighbours fail it, so the gnome swaps them and walks back past them, which reverses the order of equal values and wastes work. The textbook condition isarray[i - 1] <= array[i]. The warning in the Java section shows the cost.
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 gnome’s position, the pair it compares 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: G is the gnome,
i, and J isj, the position it will jump to when it has finished walking back. - Colours: the pair being compared is amber, or salmon when it swaps, and the values the gnome has already put in order, before
j - 1and outside the current pair, are green. - Duplicates: tick Duplicates to sort values between 0 and 3 with repeats. The small number in each cell is its original index; at the end, equal values come out in reverse order.
- Comparisons: the footer counts the comparisons.
Java Code
The implementation is a GnomeSort class with a single method, sort, which runs the whole algorithm in one while loop. Two small helpers, swap and less, live in a separate SortUtils class.
The complete code is in the algorithm-examples repository on GitHub:
GnomeSort.java, with the helpers inSortUtils.java.
sort
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Override
public <T extends Comparable<T>> T[] sort(final T[] array) {
int i = 1;
int j = 2;
while (i < array.length) {
if (SortUtils.less(array[i - 1], array[i])) {
i = j++;
} else {
SortUtils.swap(array, i - 1, i);
if (--i == 0) {
i = j++;
}
}
}
return array;
}
sort accepts an array of any Comparable type and sorts it in place. i is the gnome’s position, and j is always one step past the furthest position it has reached. When the pair (i - 1, i) is in order, i = j++ jumps to the next unvisited position and moves j on. Otherwise the pair is swapped and i steps back; if it reaches 0, there is nothing left to compare on that side, so it also jumps forward. The loop ends when i passes the last index. Empty and one-element arrays skip the loop entirely.
Two details are worth noticing:
i = j++assigns the old value ofjtoiand then incrementsj, so the gnome lands on the first position it hasn’t compared yet, andjmoves one past it.--i == 0decrementsifirst and then tests it, so the gnome jumps forward as soon as the value it was carrying has reached index 0.
Because
lessis strict, equal neighbours are treated as out of order: they are swapped, and the gnome keeps walking back past every equal value. That makes the sort unstable, since[1a, 1b]comes back as[1b, 1a], and it makes equal values quadratic: 10,000 equal values take 49,995,000 comparisons, while 10,000 sorted distinct values take 9,999. Testing!SortUtils.less(array[i], array[i - 1])instead, meaningarray[i - 1] <= array[i], fixes both.
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 loop 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 GnomeSort().sort(numbers);
System.out.println(Arrays.toString(numbers));
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Create a GnomeSort, pass it an array, and the same array comes back sorted, after 33 comparisons. The array holds Integer, not int, because the method works with Comparable objects.
Summary
- Gnome Sort is a single-loop sort: the gnome compares a pair of neighbours, steps forward when they are in order, and swaps and steps back when they aren’t.
- This implementation remembers the furthest position in
j, so after walking a value back it jumps forward instead of walking, which makes it equivalent to insertion sort with swaps. - Each time the gnome jumps forward, every value it has visited is sorted, so when it walks off the end, the whole array is.
- It runs in $O(n)$ on sorted distinct input and $O(n^2)$ otherwise, needs $O(1)$ extra space, and is in place; with this code’s strict comparison it is not stable, and equal values are quadratic.
- It is a nice exercise in writing a sort with a single loop. For real use, Insertion Sort does the same work with fewer writes, and
Arrays.sort()is faster still.
