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) {
  let i = 1;
  while (i < arr.length) {
    if (i === 0 || arr[i] >= arr[i-1]) {
      i++;
    } else {
      [arr[i], arr[i-1]] = [arr[i-1], arr[i]];
      i--;
    }
  }
}