- Gnome sort
Gnome sort is a
sorting algorithm which is similar toinsertion sort , except that moving an element to its proper place is accomplished by a series of swaps, as inbubble sort . The name comes from the supposed behavior of the Dutchgarden gnome in sorting a line of flowerpotsFact|date=October 2007 and is described on Dick Grune's [http://www.cs.vu.nl/~dick/gnomesort.html Gnome sort page]It is conceptually simple, requiring no nested loops. The running time is O("n"²), but in practice the algorithm can run as fast as
Insertion sort .The algorithm always 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 only right before or after the two swapped elements. It does not assume that elements forward of the current position are sorted, so it only needs to check the position directly before the swapped elements.
Description
Here is
pseudocode for the sort. This is an optimized version which uses variable "j" to allow the gnome to skip back to where it left off after moving to the left, avoiding some iterations and comparisons:function gnomeSort(a [0..size-1] ) { i := 1 j := 2 while i < size if a [i-1] >= a [i] "# for ascending sort, reverse the comparison to <=" i := j j := j + 1 else swap a [i-1] and a [i] i := i - 1 if i = 0 i := 1 }
Example:
If we wanted to sort an array with elements [4] [2] [7] [3] from highest to lowest, here is what would happen with each iteration of the while loop:
[4] [2] [7] [3] (initial state. i is 1 and j is 2.)
[4] [2] [7] [3] (did nothing, but now i is 2 and j is 3.)
[4] [7] [2] [3] (swapped a [2] and a [1] . now i is 1 and j is still 3.)
[7] [4] [2] [3] (swapped a [1] and a [0] . now i is 1 and j is still 3.)
[7] [4] [2] [3] (did nothing, but now i is 3 and j is 4.)
[7] [4] [3] [2] (swapped a [3] and a [2] . now i is 2 and j is 4.)
[7] [4] [3] [2] (did nothing, but now i is 4 and j is 5.)
at this point the loop ends because i isn't < 4.External links
* [http://www.cs.vu.nl/~dick/gnomesort.html Gnome sort]
Wikimedia Foundation. 2010.