希尔排序是不稳定的,大概思想为选取步长为h(这里选取h = n / 2,直到h = 1为止),
当步长为h时,对应有h个分组,对每个分组进行直接插入排序
#include<iostream> using namespace std; int a[100]; void sort1(int *a, int n); int main() { int n; while(cin >> n) { for(int i = 0; i < n; i++) cin >> a[i]; sort1(a, n); for(int i = 0; i < n; i++) cout <<" " << a[i]; cout << endl; } } void sort1(int *a, int n) { int h = n / 2;//间隔 while(h >= 1) { for(int i = 0; i < h; i++) {//当间隔为h时,共有h组,第i组 for(int j = 1; j * h + i < n; j++) {//组内进行直接插入排序 int x = a[j * h + i]; int k; for(k = j - 1; k >= 0; k--) { if(a[k * h + i] > x) a[(k + 1) * h + i] = a[k * h + i]; else break; } a[(k + 1) * h + i] = x; } } h = h / 2; } }