Gnome Sort

Works like a garden gnome sorting flower pots — moves forward when things are in order, steps back to fix when they are not.

Best O(n) Avg O(n²) Worst O(n²) Space O(1) Stable Yes In-place Yes Comparison-based

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);
}