Algorithms · Visualized
Gnome Sort
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Gnome Sort works like a garden gnome sorting flower pots: it looks at the current pot and the one before it. Time: O(n²) average, O(n²) worst; space: O(1) — sorts in place.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Gnome Sort
SortingGnome Sort works like a garden gnome sorting flower pots: it looks at the current pot and the one before it. If they're in order, it steps forward. If not, it swaps them and steps backward to re-check, just like the gnome moving back to see if the pot behind is now also out of order.
How Gnome Sort Works
- Start at position 1 (a pointer into the array).
- If the current position is 0, or the element at the current position is greater than or equal to the one before it, step forward one position.
- Otherwise, swap the current element with the previous one, and step backward one position.
- Repeat this process until the pointer reaches the end of the array.
- At that point, the array is sorted.
Gnome Sort Worked Example
Input: [5, 3, 2, 4, 1]
Pos1: 3<5 → swap → [3,5,2,4,1], step back to pos0, step forward to pos1: 5>3 ok, forward. Pos2: 2<5 → swap → [3,2,5,4,1], back to pos1: 2<3 → swap → [2,3,5,4,1], back to pos0, forward to pos1, forward to pos2. Pos3: 4<5 → swap → [2,3,4,5,1], step back and recheck... continues until fully sorted: [1,2,3,4,5].
def gnome_sort(a):
i = 1
n = len(a)
while i < n:
if a[i - 1] <= a[i]:
i += 1
else:
a[i - 1], a[i] = a[i], a[i - 1]
i -= 1
i = max(1, i)
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Gnome Sort Time & Space Complexity
When to Use Gnome Sort
- Teaching a very simple, easy-to-implement sorting idea (no nested loops needed, just one pointer).
- Situations where code simplicity matters far more than performance.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.