Back to Home

Gnome Sort

A simple sorting algorithm similar to insertion sort that works by moving elements backward until they are in the correct position.

Visualization

Step 1 / 18
Speed:

Details

Analogy

Imagine a garden gnome arranging flower pots in a line. The gnome walks forward, and if they find a pot out of order, they swap it with the previous pot and step backward. They keep stepping back and swapping until the pot is in the right place, then move forward again. The gnome continues until reaching the end of the line.

Purpose

To sort an array by moving forward through the list, and when an element is out of order, swapping it backward until it reaches its correct position. Named after the way a garden gnome sorts flower pots.

Use Cases

Primarily used for educational purposes to demonstrate sorting concepts. Good for small datasets or nearly sorted data. Its simplicity makes it easy to understand and implement, though it's not efficient for large datasets. Occasionally used in embedded systems where code simplicity is valued over performance.

Algorithm Steps

Line 1
1
function gnomeSort(array):
2
pos = 0
3
while pos < length(array):
4
if pos == 0 or array[pos] >= array[pos - 1]:
5
pos = pos + 1
6
else:
7
swap(array[pos], array[pos - 1])
8
pos = pos - 1
9
return array
Current
Executed
Pending

Explanation

What's Happening?

Step 1/18

Start at position 0 of array [5, 2, 8, 1, 9]. Position 0 is always considered sorted initially.

Updates with each step • Clickfor full view

Code Implementation

def gnome_sort(arr):
    pos = 0
    while pos < len(arr):
        if pos == 0 or arr[pos] >= arr[pos - 1]:
            pos += 1
        else:
            arr[pos], arr[pos - 1] = arr[pos - 1], arr[pos]
            pos -= 1
    return arr
Gnome Sort - Interactive Visualization | AlgoViz | AlgoViz