日本語

COMPARISON SORTS

Gnome Sort, visualised

Gnome sort moves a single position back and forth: if the element is smaller than its left neighbour it swaps and steps back, otherwise it steps forward.

Run Gnome Sort in the visualizer →

Opens the Sorting Cinema visualizer with 16 elements in English.

How it works

  1. Start at position 1.
  2. If the left neighbour is not larger, step one position right.
  3. If the left neighbour is larger, swap them and step one position left.
  4. When the position passes the right end, the array is sorted.

Complexity and stability

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

Sorted input only moves forward, O(n). Inputs that require walking far back, such as reversed input, take O(n²).

Source of facts: Complexity is derived from the steps of this app's implementation (src/SortingCinema.jsx).

Trace on a small array

The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.

#OperationArray after
1Swap [0]=5 and [1]=2[2, 5, 4, 1, 3]
2Check [0]=2[2, 5, 4, 1, 3]
3Compare [0]=2 and [1]=5[2, 5, 4, 1, 3]
4Swap [1]=5 and [2]=4[2, 4, 5, 1, 3]
5Compare [0]=2 and [1]=4[2, 4, 5, 1, 3]
6Compare [1]=4 and [2]=5[2, 4, 5, 1, 3]
7Swap [2]=5 and [3]=1[2, 4, 1, 5, 3]
8Swap [1]=4 and [2]=1[2, 1, 4, 5, 3]

…and so on. In this trace, 18 compare / swap / write operations in total produce [1, 2, 3, 4, 5].

Suitable inputs and caveats

  • Its result resembles insertion sort, but it uses a single loop and the stepping back is very visible.
  • Nearly sorted input means short walks back.
  • It swaps only when the left neighbour is strictly larger, so it is stable.

FAQ

How does gnome sort differ from insertion sort?

Both carry small values left, but gnome sort uses a single loop with one moving position that steps back one at a time after each swap.

Is gnome sort stable?

Yes. It swaps only when the left neighbour is strictly larger, so equal values keep their order.