Recent Articles



































Gnome sort



         


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. It is conceptually simple, requiring no nested loops. The running time is O(n2), and the constant has been reported to be slightly higher than Bubble sort (although this would depend on the details of the architecture and the implementation).

[Top]

Implementation

[Top]

Perl

sub gnome_sort(@) { my @a = @_; my $i=0; while ($i < @a) { if ($i==0 or $a[$i-1] <= $a[$i]) { $i++; } else { ($a[$i-1],$a[$i]) = ($a[$i],$a[$i-1]); $i--; } } return @a; }
[Top]

Python

def GnomeSort(l): i = 0 while (i < len(l)): if i == 0 or l[i - 1] <= l[i]: i += 1 else: l[i], l[i - 1] = l[i - 1], l[i] i -= 1 return l
[Top]




  View Live Article   This article is from Wikipedia. All text is available under the terms of the GNU Free Documentation License