Fork me on GitHub

排序算法@c++描述-shell排序

2.shell排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void shellSort(vector<T> &a)
{
for (int gap = a.size() / 2; gap > 0; gap /= 2) {
for (int i = gap; i < a.size(); i++) {
T tmp = a[i];
int j = i;
for (; j >= gap && tmp < a[j - gap]; j -= gap)
a[j] = a[j - gap];
a[j] = tmp;
}
}
}
int main()
{
vector<int> test = {190, 435, 834, 8954, 923, 56, 20 ,1, 934};
shellSort(test);
for (auto i : test)
cout << i << " ";
cout << endl;
return 0;
}
  • 运行结果:
    1
    2
    $ ./a.out
    1 20 56 190 435 834 923 934 8954