AlgoLab

O(n²)·O(1) space·stable
645559896316373459948511843281951114277

Starting gnome sort on an array of 20 items.

Starting gnome sort on an array of 20 items.
  1. 1if the position is at the start of the array, step forward one position
  2. 2otherwise, compare the value at the current position with the value immediately before it
  3. 3if it is smaller, swap them and step back one position
  4. 4once the position reaches the end of the array, it is fully sorted
Comparisons
0
Writes
0
Accesses
0

Complexity

BestO(n)
AverageO(n²)
WorstO(n²)
Extra spaceO(1)
StableYes
n² at n=20 predicts 400; this run took 0.

Gnome sort

Gnome sort keeps one position and repeatedly compares the value there with the value immediately before it. If they are in order, or the position is at the start of the array, it steps forward. If they are out of order, it swaps them and steps back one position to check again. There is no remembered key value and no separate inner loop — insertion sort's shifting is replaced by a sequence of single swaps and backward steps that has exactly the same net effect.

When it is the right choice

Gnome sort is not a serious choice for real work: it performs the same O(n²) comparisons and writes as bubble sort or insertion sort, with no offsetting advantage. Its value is entirely pedagogical — it is the shortest correct sorting algorithm to write and to trace by hand, useful for building intuition about what a sort has to guarantee before reaching for a faster one.

How it works

Worth noticing

Cost

Best
O(n)
Average
O(n²)
Worst
O(n²)
Extra space
O(1)
Stable
Yes

Worth comparing

All algorithms