Sorting Algorithm
Gnome Sort
“The Indecisive Gardener”
History
Originally called "Stupid Sort" (no, really) by Hamid Sarbazi-Azad in 2000, it was rebranded as Gnome Sort by Dick Grune. The metaphor is a garden gnome sorting flower pots. He looks at two pots. If they are out of order, he swaps them and steps back. If they are fine, he steps forward.
It is essentially Insertion Sort implemented by someone who hates nested loops.
How It Works
Gnome Sort uses a single index variable. It's a state machine with just two rules: move forward if things look good, move backward if you made a swap.
The Algorithm Step-by-Step
- Start: At index 0.
- Check: Compare current pot with previous pot.
- Good?: If they are in order (or we are at start), step forward.
- Bad?: If they are out of order, swap them and step backward.
- Repeat: Until you reach the end.
Connection to Insertion Sort
It produces the exact same sequence of swaps as Insertion Sort, but instead of an inner loop, it physically moves the "cursor" back and forth.
If sorted, the gnome just walks from start to finish without stopping.
The gnome spends most of his life walking backwards. It's painfully slow.
Same as Insertion Sort, but usually slightly slower due to the overhead of variable updates.
In-place. Only needs one index tracker.
Code Walkthrough
Real implementations in multiple programming languages. Select a language to view idiomatic code.
1def gnome_sort(arr: list[int]) -> None:2 """Sort array in-place using gnome sort."""3 n = len(arr)4 i = 056 while i < n:7 if i == 0:8 i += 19 elif arr[i] >= arr[i - 1]:10 # In order - move forward11 i += 112 else:13 # Out of order - swap and move backward14 arr[i], arr[i - 1] = arr[i - 1], arr[i]15 i -= 1Real World Use Cases
- 1Code Golf (sorting in as few lines as possible)
- 2Teaching algorithm concepts
- 3Situations where code complexity is the enemy, not time
- 4Sorting arrays on very primitive hardware
Key Insights
- It has no nested loops (a rarity for sorts).
- It is stable.
- It is conceptually simple but practically inefficient.
- It's mostly a novelty.
When to Use
When you need to write a sort function in 5 lines of code and you don't care how fast it runs. Or when you want to confuse an interviewer.
When NOT to Use
In production. Just use Insertion Sort.
Related Algorithms
Try It Yourself
Watch how this algorithm behaves on different inputs. Click a demo to launch the visualizer.