Sorting algorithms/Gnome sort
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
Heap sort | Merge sort | Patience sort | Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
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; } }
}
- undef swap_</lang>