Sorting algorithms/Gnome sort

From Rosetta Code
Revision as of 10:34, 27 April 2009 by rosettacode>ShinTakezou (gnome sort (with C code))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Sorting algorithms/Gnome sort
You are encouraged to solve this task according to the task description, using any language you may know.
This page uses content from Wikipedia. The original article was at Sorting algorithms/Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)

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 pseudocode for the algorithm is:

 function gnomeSort(a[0..size-1]) {
  i := 1
  j := 2
  while i < size
    if a[i-1] <= a[i] # for descending 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 := j
          j := j + 1
 }

Task: implement the Gnome sort in your language to sort an array (or list) of numbers.

C

This algorithm sorts in place modifying the passed array (of n integer numbers).

<lang c>#define swap_(I,J) do { int t_; t_ = a[(I)]; \

     a[(I)] = a[(J)]; a[(J)] = t_; } while(0)

void gnome_sort(int *a, int n) {

 int i=1, j=2;

 while(i < n) {
   if ( a[i-1] <= a[i] ) {
     i = j; j++;
   } else {
     swap_(i-1, i);
     i--;
     i = (i==0) ? 1 : i;
   }
 }

}

  1. undef swap_</lang>