Gnome sort maintains a sorted prefix with one index. If a[i-1] <= a[i], the index advances. If the pair is inverted, the values swap and the index steps back so the displaced value can continue moving toward its insertion point. Reaching index 0 immediately resumes at 1.

The mechanism is Insertion Sort expressed through adjacent swaps rather than shifting a saved value. Each swap removes one inversion, so the process terminates. Strict comparison keeps equal values from crossing, making the sort stable.

Visualization

Forward steps confirm the current prefix remains ordered. A swap steps back by one position; repeated swaps walk the smaller value left until its predecessor is no greater, after which the scan moves forward again.

Complexity
n
number of elements in the array

Boundary and implementation

Ordered input needs one forward scan, but reverse-ordered input contains n(n-1)/2 inversions and forces that many adjacent swaps. Insertion Sort reaches the same asymptotic bound with fewer writes because it shifts a block and writes the inserted value once; Gnome Sort is mainly useful for seeing inversion removal in a single loop.

Questions

References