Gnome sort (nicknamed stupid sort) is a variation of the insertion sort sorting algorithm that does not use nested loops. Gnome sort was originally proposed by Iranian computer scientist Hamid Sarbazi-Azad (professor of Computer Science and Engineering at Sharif University of Technology) in 2000. The sort was first called stupid sort (not to be confused with bogosort), and then later described by Dick Grune and named gnome sort.
|Worst-case space complexity||auxiliary|
Gnome sort performs at least as many comparisons as insertion sort and has the same asymptotic runtime characteristics. Gnome sort works by building a sorted list one element at a time, getting each item to the proper place in a series of swaps. The average running time is O(n2) but tends towards O(n) if the list is initially almost sorted.[note 1]
Gnome Sort is based on the technique used by the standard Dutch Garden Gnome (Du.: tuinkabouter).
Here is how a garden gnome sorts a line of flower pots.
Basically, he looks at the flower pot next to him and the previous one; if they are in the right order he steps one pot forward, otherwise, he swaps them and steps one pot backward.
Boundary conditions: if there is no previous pot, he steps forwards; if there is no pot next to him, he is done.— "Gnome Sort - The Simplest Sort Algorithm". Dickgrune.com
procedure gnomeSort(a): pos := 0 while pos < length(a): if (pos == 0 or a[pos] >= a[pos-1]): pos := pos + 1 else: swap a[pos] and a[pos-1] pos := pos - 1
Given an unsorted array, a = [5, 3, 2, 4], the gnome sort takes the following steps during the while loop. The current position is highlighted in bold and indicated as a value of the variable
||Condition in effect||Action to take|
|[5, 3, 2, 4]||0||pos == 0||increment pos|
|[5, 3, 2, 4]||1||a[pos] < a[pos-1]||swap, decrement pos|
|[3, 5, 2, 4]||0||pos == 0||increment pos|
|[3, 5, 2, 4]||1||a[pos] ≥ a[pos-1]||increment pos|
|[3, 5, 2, 4]||2||a[pos] < a[pos-1]||swap, decrement pos|
|[3, 2, 5, 4]||1||a[pos] < a[pos-1]||swap, decrement pos|
|[2, 3, 5, 4]||0||pos == 0||increment pos|
|[2, 3, 5, 4]||1||a[pos] ≥ a[pos-1]||increment pos|
|[2, 3, 5, 4]||2||a[pos] ≥ a[pos-1]||increment pos:|
|[2, 3, 5, 4]||3||a[pos] < a[pos-1]||swap, decrement pos|
|[2, 3, 4, 5]||2||a[pos] ≥ a[pos-1]||increment pos|
|[2, 3, 4, 5]||3||a[pos] ≥ a[pos-1]||increment pos|
|[2, 3, 4, 5]||4||pos == length(a)||finished|
|The Wikibook Algorithm implementation has a page on the topic of: Gnome sort|