function gnomeSort(array: number[]) {let index = 0;
while (index < array.length) { if (index === 0 || array[index - 1] <= array[index]) {index++;
} else {swap(array, index - 1, index);
index--;
}
}
}
Start at index 0. The gnome keeps everything left of it sorted.
Understanding Gnome sort
The idea
Gnome sort has one pointer and one rule. If the element under the pointer is not smaller than the one before it, step forward; otherwise swap the two and step back. Everything to the left of the pointer is always sorted, so when the pointer walks off the end the array is done.
It is insertion sort written without a nested loop: the stepping back is the inner loop, done with swaps instead of shifts. Same comparisons, more writes, and a listing short enough to remember.
The four stages
Complexity
Versus its siblings
Pseudocode
GNOMESORT(array)
index ← 0
while index < n
if index = 0 or array[index − 1] ≤ array[index]: index ← index + 1
else: swap array[index − 1], array[index]; index ← index − 1
When to use
Pitfalls
History
Hamid Sarbazi-Azad described it in 2000 as stupid sort; Dick Grune renamed it gnome sort after the Dutch garden gnome who sorts flower pots by looking at the pot next to him. It is the simplest correct sorting loop that can be written.