Gnome sort




Gnome sort is a sorting algorithm originally proposed by an Iranian computer scientist Hamid Sarbazi-Azad in 2000. The sort was first called stupid sort, and then later described by Dick Grune and named gnome sort.
The gnome sort is a sorting algorithm which is similar to insertion sort in that it works with one item at a time but gets the item to the proper place by a series of swaps, similar to a bubble sort. It is conceptually simple, requiring no nested loops. The average running time is O but tends towards O if the list is initially almost sorted.
The algorithm finds the first place where two adjacent elements are in the wrong order and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair next to the previously swapped elements. It does not assume that elements forward of the current position are sorted, so it only needs to check the position directly previous to the swapped elements.

Description

described the sorting method with the following story:

Code

Here is pseudocode for the gnome sort using a zero-based array:

procedure gnomeSort:
pos := 0
while pos < length:
if :
pos := pos + 1
else:
swap a and a
pos := pos - 1

Example

Given an unsorted array, a = , 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 pos.
Current arrayposCondition in effectAction to take
0pos 0increment pos
1a < aswap, decrement pos
0pos 0increment pos
1a ≥ aincrement pos
2a < aswap, decrement pos
1a < aswap, decrement pos
0pos 0increment pos
1a ≥ aincrement pos
2a ≥ aincrement pos:
3a < aswap, decrement pos
2a ≥ aincrement pos
3a ≥ aincrement pos
4pos lengthfinished

Optimization

The gnome sort may be optimized by introducing a variable to store the position before traversing back toward the beginning of the list. With this optimization, the gnome sort would become a variant of the insertion sort.
Here is pseudocode for an optimized gnome sort using a zero-based array:

procedure optimizedGnomeSort:
for pos in 1 to length:
gnomeSort
procedure gnomeSort:
pos := upperBound
while pos > 0 and a > a:
swap a and a
pos := pos - 1