隨筆 - 312, 文章 - 14, 評論 - 1393, 引用 - 0
          數(shù)據(jù)加載中……

          希爾排序(shellsort)算法實(shí)現(xiàn)

              希爾排序(shellsort)又叫增量遞減(diminishing increment)排序,是由D.L. Shell發(fā)明的,這個(gè)算法是通過一個(gè)逐漸減小的增量使一個(gè)數(shù)組逐漸趨近于有序從而達(dá)到排序的目的。

                假設(shè)有一個(gè)數(shù)組int data[16] = {...}。 首先將這個(gè)增量設(shè)為16 / 2 = 8, 這樣就將這個(gè)數(shù)組分成了8個(gè)子數(shù)組,它們的索引是0, 8    1, 9   2, 10等等 。對這些子數(shù)組進(jìn)行排序。然后再使增量為8 / 2 = 4,這樣就將原數(shù)組分成了4個(gè)子數(shù)組,它們的索引分別是0, 4, 8, 12    1, 5, 9, 13等等。再對這四組數(shù)進(jìn)行排序,直到增量為1。
               以上所描述的增量遞減只是一種方法,這種方法并不是最有效率的。如f(n) = 3 * f(n - 1) + 1  f(1) = 1   (..., 121, 40, 13,  4, 1)就比上面的取增量的方法好。這種方法的時(shí)間復(fù)雜度是O(n ^1.5)

          算法如下

          #include <stdio.h>

          void output_array(int data[], int n)
          {
              
          int i;
              
          for(i = 0; i < n; i++)
                  printf(
          "%d ", data[i]);
              printf(
          "\n");
          }
          void swap(int *a, int *b)
          {
              
          int x;
              x 
          = *a;
              
          *= *b;
              
          *= x;
          }
          void insertion_sort(int data[], int n, int increment)
          {
              
          int i, j;
              
          for(i = increment; i < n; i += increment)
                  
          for(j = i; j >= increment && data[j] > data[j - increment]; j -= increment)
                      swap(
          &data[j], &data[j - increment]);
          }
          void shellsort(int data[], int n)
          {
              
          int i, j;
              
          for(i = n / 2; i > 2; i /= 2)
                  
          for(j = 0; j < i; j++)
                      insertion_sort(data 
          + j, n - j, i);
              insertion_sort(data, n, 
          1);
          }
          int main()
          {
              
          int data[] = {5316657766441110986};
              output_array(data, 
          12);
              shellsort(data, 
          12);
              output_array(data, 
          12);
              
          return 0;
          }




          Android開發(fā)完全講義(第2版)(本書版權(quán)已輸出到臺灣)

          http://product.dangdang.com/product.aspx?product_id=22741502



          Android高薪之路:Android程序員面試寶典 http://book.360buy.com/10970314.html


          新浪微博:http://t.sina.com.cn/androidguy   昵稱:李寧_Lining

          posted on 2008-05-15 22:01 銀河使者 閱讀(2398) 評論(1)  編輯  收藏 所屬分類: algorithm 、C/C++

          評論

          # re: 希爾排序(shellsort)算法實(shí)現(xiàn)  回復(fù)  更多評論   

          這是最標(biāo)準(zhǔn)的算法
          2008-05-16 12:08 | 網(wǎng)上買書
          主站蜘蛛池模板: 海宁市| 永修县| 元氏县| 九江县| 衡南县| 东城区| 大关县| 蒙山县| 泰安市| 侯马市| 信阳市| 石阡县| 东海县| 怀集县| 循化| 黔江区| 盐源县| 仪陇县| 镇雄县| 色达县| 韶山市| 乌审旗| 铁岭市| 察哈| 阿坝| 赤水市| 沁阳市| 应用必备| 文山县| 宜城市| 吐鲁番市| 玉门市| 明溪县| 手机| 桓台县| 白玉县| 高台县| 鄢陵县| 大城县| 兴化市| 福州市|