运维结果为

动用希尔增量时排序的最坏为:O(n^2);

代码如下:

 1 #include <iostream>
 2 #include <vector>
 3 using namespace std;
 4 template <typename Comparable>
 5 void shellsort(vector<Comparable> & a)
 6 {
 7     for(int gap = a.size()/2; gap > 0; gap /= 2)
 8         for(int i = gap; i < a.size() ; i++)
 9         {
10             Comparable tmp = a[i];
11             int j = i;
12 
13             for( ; j>=gap && tmp<a[j-gap] ; j -= gap)
14                 a[j] = a[j-gap];
15             a[j]=tmp;
16         }
17 }
18 int main()
19 {
20     vector<int> ivec;
21     ivec.push_back(1);
22     ivec.push_back(9);
23     ivec.push_back(2);
24     ivec.push_back(10);
25     ivec.push_back(3);
26     ivec.push_back(11);
27     ivec.push_back(4);
28     ivec.push_back(12);
29     ivec.push_back(5);
30     ivec.push_back(13);
31     ivec.push_back(6);
32     ivec.push_back(14);
33     ivec.push_back(7);
34     ivec.push_back(15);
35     ivec.push_back(8);
36     ivec.push_back(16);
37     shellsort(ivec);
38     for(int i=0;i<ivec.size();i++)
39         cout<<ivec[i]<<endl;
40     return 0;
41 }

运转结果为:

图片 1

相关文章