vector<int> ShellSort(vector<int> list) { vector<int> result = list; int n = result.size(); for (int gap = n >> 1; gap > 0; gap >>= 1) { //下面的代码就是插入排序,只是将增量从1改为gap了,这里gap表示的是增量 for (int i = gap; i < n; i++) { int temp = result[i]; int j = i - gap; while (j >= 0 && result[j] > temp) { result[j + gap] = result[j]; j -= gap;//只比较在这个增量下选出来的一个组中的元素大小 } result[j + gap] = temp; } } return result; }
intmain() { int arr[] = {6, 4, 8, 9, 2, 3, 1}; vector<int> test(arr, arr + sizeof(arr) / sizeof(arr[0])); cout << "排序前" << endl; for (int i = 0; i < test.size(); i++) { cout << test[i] << " "; } cout << endl; vector<int> result; result = ShellSort(test); cout << "排序后" << endl; for (int i = 0; i < result.size(); i++) { cout << result[i] << " "; } }