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
- Start at position 1.
- If the left neighbour is not larger, step one position right.
- If the left neighbour is larger, swap them and step one position left.
- 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.
| # | Operation | Array after |
|---|---|---|
| 1 | Swap [0]=5 and [1]=2 | [2, 5, 4, 1, 3] |
| 2 | Check [0]=2 | [2, 5, 4, 1, 3] |
| 3 | Compare [0]=2 and [1]=5 | [2, 5, 4, 1, 3] |
| 4 | Swap [1]=5 and [2]=4 | [2, 4, 5, 1, 3] |
| 5 | Compare [0]=2 and [1]=4 | [2, 4, 5, 1, 3] |
| 6 | Compare [1]=4 and [2]=5 | [2, 4, 5, 1, 3] |
| 7 | Swap [2]=5 and [3]=1 | [2, 4, 1, 5, 3] |
| 8 | Swap [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.