Gnome sort

From Wikipedia, the free encyclopedia

Gnome sort is a sorting algorithm which is similar to insertion sort except that moving an element to its proper place is accomplished by a series of swaps, as in bubble sort. The name comes from the supposed behavior of the Dutch garden gnome in sorting a line of flowerpots. It is conceptually simple, requiring no nested loops. The running time is O(n2), and in practice the algorithm has been reported to generally run slightly slower than bubble sort, although this depends on the details of the architecture and the implementation.

[edit] Description

Here is pseudocode for the sort:

 function gnomeSort(a[1..size]) {
  i := 2
  while i ≤ size
    if a[i-1] ≤ a[i]
        i := i + 1
    else
        swap a[i-1] and a[i]
        i := i - 1
        if i = 1
          i := 2
 }

Effectively, the algorithm always finds the first place where two adjacent elements are in the wrong order, and swaps them. If this place were searched for naively, the result would be O(n3). Instead, it takes advantage of the fact that performing a swap can only introduce a new out-of-order adjacent pair right before the two swapped elements, and so checks this position immediately after performing such a swap.


[edit] External link

In other languages