难度较大。
#include <iostream>
using namespace std;
void swap(int& a, int& b)
{
int temp = 0;
temp = a;
a = b;
b = temp;
}
void print_array(int a[], int n)
{
for (int i = 0; i < n; i++)
{
cout << a[i] << " ";
}
cout << endl;
}
void shell_sort(int arr[], int len)
{
int i=0, j = 0, inc = 0, key = 0;
// 初始增量:len/2,每一趟之后除以二
for (inc = len / 2; inc > 0; inc /= 2) //6 3 1
{
// 每一趟采用插入排序
for (i = inc; i < len; i++)
{
key = arr[i];
for (j = i; j >= inc && key < arr[j - inc]; j -= inc)
arr[j] = arr[j - inc];
arr[j] = key;
}
}
print_array(arr, len);
}
int main(void)
{
int a[] = { 15,5,2,7,12,6,1,4,3,9,8,10 };
shell_sort(a, 12);
return 0;
}