algoalgo-world
algoalgo-world/sort/gnome-sort
sort/gnome-sort

侏儒排序

最好
O(n)
平均
O(n^2)
最坏
O(n^2)
空间
O(1)
稳定性
稳定
方式
比较

选一种语言就能看到代码

def gnome_sort(a):
    i = 0
    while i < len(a):
        if i == 0 or a[i - 1] <= a[i]:
            i += 1
        else:
            a[i - 1], a[i] = a[i], a[i - 1]
            i -= 1
function gnomeSort(a) {
  let i = 0;
  while (i < a.length) {
    if (i === 0 || a[i - 1] <= a[i]) {
      i++;
    } else {
      [a[i - 1], a[i]] = [a[i], a[i - 1]];
      i--;
    }
  }
}
static void swap(int a[], int i, int j) {
    int t = a[i];
    a[i] = a[j];
    a[j] = t;
}

void gnome_sort(int a[], int n) {
    int i = 0;
    while (i < n) {
        if (i == 0 || a[i - 1] <= a[i]) {
            i++;
        } else {
            swap(a, i - 1, i);
            i--;
        }
    }
}
void gnome_sort(std::vector<int>& a) {
    size_t i = 0;
    while (i < a.size()) {
        if (i == 0 || a[i - 1] <= a[i]) {
            i++;
        } else {
            std::swap(a[i - 1], a[i]);
            i--;
        }
    }
}
static void GnomeSort(int[] a) {
    int i = 0;
    while (i < a.Length) {
        if (i == 0 || a[i - 1] <= a[i]) {
            i++;
        } else {
            (a[i - 1], a[i]) = (a[i], a[i - 1]);
            i--;
        }
    }
}
static void swap(int[] a, int i, int j) {
    int t = a[i];
    a[i] = a[j];
    a[j] = t;
}

static void gnomeSort(int[] a) {
    int i = 0;
    while (i < a.length) {
        if (i == 0 || a[i - 1] <= a[i]) {
            i++;
        } else {
            swap(a, i - 1, i);
            i--;
        }
    }
}
先跑一遍,再读源码