Jump to content

Gnome sort: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
No edit summary
Citation bot (talk | contribs)
Altered archive-url. URLs might have been anonymized. | Use this bot. Report bugs. | Suggested by Dominic3203 | Category:Stable sorts | #UCB_Category 10/18
 
(382 intermediate revisions by more than 100 users not shown)
Line 1: Line 1:
{{Short description|Sorting algorithm}}
'''Gnome sort''' is a [[sort 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.
{{Refimprove|date=August 2010}}
It is conceptually simple, requiring no nested loops. The running time is [[Big O notation|O]](''n''<sup>2</sup>), and in practice the algorithm has been reported to run slightly slower than [[bubble sort]], although this depends on the details of the architecture and the implementation.


{{Infobox Algorithm
== Description ==
|name={{PAGENAMEBASE}}|class=[[Sorting algorithm]]
Here is pseudocode for the sort:
|image=Visualization of Gnome sort.gif
|caption=Visualisation of Gnome sort
|data=[[Array data structure|Array]]
|time=<math>O(n^2)</math>
|best-time=<math>O(n)</math>
|average-time= <math>O(n^2)</math>
|space= <math>O(1)</math> auxiliary
}}
'''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 [[Iran]]ian computer scientist [[Hamid Sarbazi-Azad]] (professor of Computer Science and Engineering at [[Sharif University of Technology]])<ref>{{Cite web|url=http://sharif.edu/~azad/|title=Hamid Sarbazi-Azad profile page|last=Hamid|first=Sarbazi-Azad|archive-url=https://web.archive.org/web/20181016164904/http://sharif.edu/~azad/|archive-date=2018-10-16|url-status=live|access-date=October 16, 2018}}</ref> in 2000. The sort was first called ''stupid sort''<ref>{{cite journal
|last = Sarbazi-Azad
|first = Hamid
|date = 2 October 2000
|title = Stupid Sort: A new sorting algorithm
|url = http://sina.sharif.edu/~azad/stupid-sort.PDF
|journal = Newsletter
|publisher = Computing Science Department, Univ. of Glasgow
|issue = 599
|page = 4
|access-date = 25 November 2014
|archive-url = https://web.archive.org/web/20120307235904/http://sina.sharif.edu/~azad/stupid-sort.PDF
|archive-date = 7 March 2012
|url-status = live
}}</ref> (not to be confused with [[bogosort]]), and then later described by [[Dick Grune]] and named ''gnome sort''.<ref name="DGrune">{{cite web |url=http://www.dickgrune.com/Programs/gnomesort.html |title=Gnome Sort - The Simplest Sort Algorithm |website=Dickgrune.com |date=2000-10-02 |access-date=2017-07-20 |archive-url=https://web.archive.org/web/20170831222005/https://dickgrune.com/Programs/gnomesort.html |archive-date=2017-08-31 |url-status=live }}</ref>


Gnome sort performs at least as many comparisons as [[insertion sort]] and has the same [[asymptotic run time]] 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 [[Big O notation|''O'']](''n''<sup>2</sup>) but tends towards ''O''(''n'') if the list is initially almost sorted.<ref>{{cite web
'''function''' gnomeSort(a[1..size]) {
|url = http://xlinux.nist.gov/dads/HTML/gnomeSort.html
i := 2
|title = gnome sort
'''while''' i &le; size
|work = Dictionary of Algorithms and Data Structures
'''if''' a[i-1] &le; a[i]
|publisher = U.S. National Institute of Standards and Technology
i := i + 1
|author = Paul E. Black
'''else'''
|access-date = 2011-08-20
swap a[i-1] and a[i]
|archive-url = https://web.archive.org/web/20110811012120/http://xlinux.nist.gov/dads//HTML/gnomeSort.html
i := i - 1
|archive-date = 2011-08-11
'''if''' i = 1
i := 2
|url-status = live
}}</ref><ref group="note">''Almost sorted'' means that each item in the list is not far from its proper position (not farther than some small constant distance).</ref>
}


[[Dick Grune]] described the sorting method with the following story:<ref name="DGrune" />
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(n<sup>3</sup>). 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.


{{quote|
==Implementations==
Gnome Sort is based on the technique used by the standard Dutch [[garden gnome|Garden Gnome]] (Du.: [[:nl:tuinkabouter|tuinkabouter]]). <br />
===[[C Sharp|C#]]===
Here is how a garden gnome sorts a line of [[flowerpot|flower pots]]. <br />
void GnomeSort( int[] array )
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. <br />
{
Boundary conditions: if there is no previous pot, he steps forwards; if there is no pot next to him, he is done.
for ( int i = 1; temp_value; i < array.Length; )
|sign=| source="Gnome Sort - The Simplest Sort Algorithm". ''Dickgrune.com''}}
{
if ( array[i-1] <= array[i] )
i += 1;
else
{
temp_value = array[i-1];
array[i-1] = array[i];
array[i] = temp_value;
i -= 1;
if ( i == 0 )
i = 1;
}
}
}


===[[C++]]===
== Pseudocode ==
Here is [[pseudocode]] for the gnome sort using a [[zero-based array]]:
#include <algorithm> // for std::swap
void gnomeSort( int* array, int size )
{
for ( int i = 1; i < size; ) {
if ( array[i-1] <= array[i] ) {
++i;
}
else {
std::swap( array[i-1], array[i] );
--i;
if ( i == 0 ) {
i = 1;
}
}
}
}


'''procedure''' gnomeSort(a[]):
===[[Perl programming language|Perl]]===
pos := 0
sub gnome_sort(@)
'''while''' pos < length(a):
{
'''if''' (pos == 0 '''or''' a[pos] >= a[pos-1]):
my @a = @_;
my $i = 1;
pos := pos + 1
while ($i < @a) {
'''else''':
if ($a[$i-1] <= $a[$i]) {
'''swap''' a[pos] '''and''' a[pos-1]
$i++;
pos := pos - 1
}
else {
@a[$i-1, $i] = @a[$i, $i-1];
$i--;
$i = 1 if $i == 0;
}
}
return @a;
}


===Example===
===[[Python programming language|Python]]===
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 <code>pos</code>.
def gnome_sort(L):
L = L[:]
i = 1
while i < len(L):
if L[i-1] <= L[i]:
i += 1
else:
L[i], L[i-1] = L[i-1], L[i]
i -= 1
if i == 0:
i = 1
return L


{| class="wikitable"
===[[FORTRAN 77]]===
|-
SUBROUTINE gnome_sort(A, LEN)
! Current array
INTEGER A, LEN, I, TEMP
! <code>pos</code>
DIMENSION A(LEN)
! Condition in effect
I = 2
! Action to take
WHILE (I .LE. LEN) DO
|-
IF ((I .EQ. 1) .OR. (A(I-1) .LE. A(I))) THEN
|| ['''5''', 3, 2, 4] || 0 || pos == 0 || increment pos
I = I + 1
|-
ELSE
|| [5, '''3''', 2, 4] || 1 || a[pos] < a[pos-1] || swap, decrement pos
TEMP = A(I)
|-
A(I) = A(I-1)
|| ['''3''', 5, 2, 4] || 0 || pos == 0 || increment pos
A(I-1) = TEMP
|-
I = I - 1
|| [3, '''5''', 2, 4] || 1 || a[pos] ≥ a[pos-1] || increment pos
IF (I .EQ. 1) THEN
|-
I = 2
|| [3, 5, '''2''', 4] || 2 || a[pos] < a[pos-1] || swap, decrement pos
END IF
|-
END IF
|| [3, '''2''', 5, 4] || 1 || a[pos] < a[pos-1] || swap, decrement pos
END WHILE
|-
END
|| ['''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
|}


===[[Java]]===
==Notes==
{{reflist|group=note}}
public class GnomeSort {
==References==
static void gnomeSort( int[] theArray ) {
{{Reflist}}
for ( int index = 1; index < theArray.length; ) {
if ( theArray[index - 1] <= theArray[index] ) {
++index;
} else {
int tempVal = theArray[index];
theArray[index] = theArray[index - 1];
theArray[index - 1] = tempVal;
--index;
if ( index == 0 ) {
index = 1;
}
}
}
}
}


==External links==
{{wikibooks|Algorithm implementation|Sorting/Gnome_sort|Gnome sort}}
* [http://dickgrune.com/Programs/gnomesort.html Gnome sort]


{{sorting}}
==External link==
* [http://www.cs.vu.nl/~dick/gnomesort.html Gnome sort].


{{DEFAULTSORT:Gnome Sort}}

[[Category:Sort algorithms]]
[[Category:Comparison sorts]]
[[Category:Stable sorts]]

[[pt:Gnome sort]]

Latest revision as of 09:58, 24 October 2024

Gnome sort
Visualisation of Gnome sort
ClassSorting algorithm
Data structureArray
Worst-case performance
Best-case performance
Average performance
Worst-case space complexity auxiliary

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)[1] in 2000. The sort was first called stupid sort[2] (not to be confused with bogosort), and then later described by Dick Grune and named gnome sort.[3]

Gnome sort performs at least as many comparisons as insertion sort and has the same asymptotic run time 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.[4][note 1]

Dick Grune described the sorting method with the following story:[3]

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

Pseudocode

[edit]

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

 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

Example

[edit]

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 pos.

Current array pos 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

Notes

[edit]
  1. ^ Almost sorted means that each item in the list is not far from its proper position (not farther than some small constant distance).

References

[edit]
  1. ^ Hamid, Sarbazi-Azad. "Hamid Sarbazi-Azad profile page". Archived from the original on 2018-10-16. Retrieved October 16, 2018.
  2. ^ Sarbazi-Azad, Hamid (2 October 2000). "Stupid Sort: A new sorting algorithm" (PDF). Newsletter (599). Computing Science Department, Univ. of Glasgow: 4. Archived (PDF) from the original on 7 March 2012. Retrieved 25 November 2014.
  3. ^ a b "Gnome Sort - The Simplest Sort Algorithm". Dickgrune.com. 2000-10-02. Archived from the original on 2017-08-31. Retrieved 2017-07-20.
  4. ^ Paul E. Black. "gnome sort". Dictionary of Algorithms and Data Structures. U.S. National Institute of Standards and Technology. Archived from the original on 2011-08-11. Retrieved 2011-08-20.
[edit]