How it works
Works like a garden gnome sorting flower pots — moves forward when things are in order, steps back to fix when they are not.
Implementation
function gnomeSort(arr, stats) { const n = arr.length; let i = 1; while (i < n) { if (i === 0) { i++; } else { compare(i, i - 1); if (arr[i] >= arr[i - 1]) { i++; } else { swap(i, i - 1); let tmp = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = tmp; i--; } } checkpoint(i, n); } for (let i = 0; i < n; i++) markSorted(i); }
def gnomeSort(arr, stats): i = 1 while (i < n): if (i == 0): i += 1 else: compare(i, (i - 1)) if (arr[i] >= arr[(i - 1)]): i += 1 else: swap(i, (i - 1)) arr[i], arr[(i - 1)] = arr[(i - 1)], arr[i] i -= 1 checkpoint(i, n) for i in range(n): markSorted(i)
#include <vector> #include <algorithm> void sort(std::vector<int>& arr, int n, int& comparisons, int& swaps) { int i = 1; while((i < n)) { if((i == 0)) { i++; } else { compare(i, (i - 1)); if((arr[i] >= arr[(i - 1)])) { i++; } else { swap(i, (i - 1)); std::swap(arr[i], arr[(i - 1)]); i--; } } checkpoint(i, n); } for(int i=0; i<n; i++) { markSorted(i); } }
public void Sort(int[] arr, int n, dynamic stats) { int i = 1; while((i < n)) { if((i == 0)) { i++; } else { compare(i, (i - 1)); if((arr[i] >= arr[(i - 1)])) { i++; } else { swap(i, (i - 1)); { int _t = arr[i]; arr[i] = arr[(i - 1)]; arr[(i - 1)] = _t; } i--; } } checkpoint(i, n); } for(int i=0; i<n; i++) { markSorted(i); } }
#include <stdio.h> void sort(int arr[], int n, int* comparisons, int* swaps) { int i = 1; while((i < n)) { if((i == 0)) { i++; } else { compare(i, (i - 1)); if((arr[i] >= arr[(i - 1)])) { i++; } else { swap(i, (i - 1)); { int _t = arr[i]; arr[i] = arr[(i - 1)]; arr[(i - 1)] = _t; } i--; } } checkpoint(i, n); } for(int i=0; i<n; i++) { markSorted(i); } }