插入排序及升级版希尔排序

 1 //直接快插法,最好情况每次插入数据就在最后时间复杂度为O(n),最坏情况为每次插入数据为最小,
 2 //每次移动最大次数及时间复杂度为O(n2)
 3 void InsertSort(int array[], int n)
 4 {
 5     int i, j;
 6     for (i = 1; i < n; ++i)//从第二个数据开始,默认第一个数据已经有序
 7     {
 8         int tenp = array[i];//将要插入数据先寄存
 9         j = i;
10         while (j >0 && tenp < array[j-1])
11         {
12             array[j] = array[j-1];//数据后移
13             --j;
14         }
15         array[j] = tenp;//插入到正确位置
16     }
17 }
18 
19 //插入排序升级版希尔排序
20 void ShellSort(int array[], int n)  
21 {
22     /*//大话数据结构示例
23     int i, j, temp;
24     int increment = n;
25     do {
26         increment = increment / 3 + 1;
27         for (i = increment + 1; i <= n; ++i)
28         {
29             if (array[i] < array[i - increment])
30             {
31                 temp = array[i];
32                 j = i - increment;
33                 while(j > 0 && array[j] > temp)
34                 {
35                     array[j + increment] = array[j];
36                     j -= increment;              
37                 }
38                 array[j + increment] = temp;
39             }
40         }
41     } while (increment > 1);*/
42 
43     int i, j;
44     int step = n;
45     for (step = step / 2; step > 0; step = step / 2)  //这里的step步长是根据元素个数这种情况定义的
46     {        
47         for (i = step; i < n; ++i)
48         {
49             if (array[i] < array[i - step])
50             {
51                 int temp = array[i]; //把数组下标i的值放到temp中
52                 j = i;
53                 while (j >= step && array[j - step] > temp)
54                 {
55                     array[j] = array[j - step]; //把大的值往后插入
56                     j -= step;
57                 }
58                 array[j] = temp; //把小的值往前插入
59             }           
60         }       
61     }
62 }
63 //希尔排序的时间复杂取决于增量序列,但是它已经突破了为O(n2);

 

posted @ 2020-06-23 14:56  dhhu007  阅读(76)  评论(0编辑  收藏  举报