希尔排序

来源:互联网 发布:台州学院网络教学平台 编辑:程序博客网 时间:2024/05/24 06:53

转自:http://blog.csdn.net/21aspnet/article/details/1534410

[cpp] view plaincopy
  1. #include <stdio.h>;  
  2.   
  3. void Shell_Sort(int a[], int n)   
  4. {   
  5.     int h,i,j,temp;   //h为间隔,temp暂存要插入的数据项
  6.     //分为由粗到细的插入排序,这是希尔相对插入排序的特色。
        //共要完成(log2 n)次的插入排序,每次需排序的长度加1,每次插入排序要插入count-h 个数据
  7.     for (h=n/2; h>0; h=h/2)   // 1/2 = 0 这时就会跳出循环-----获取间隔,同一间隔的为一大组
  8.     {   
  9.         //先将从h 开始的以后的数按照插入排序一一插入从前面以h 为间隔选出的小组中,
    //完成一次粗排序,粗细程度由间隔h 决定!
  10.         for (i=h; i<n; i++)   //移动获取新的插入项------ ,移动扫描,获取新的数据项和大组数据( h之前的即为大组)
  11.         {   
  12.        //特殊的插入排序,并不是一个个的比较然后移动,而是以h 为间隔的比较、移动和插入a[i]
  13.            temp = a[i];   //暂存要插入的数据项,此插入数据项是不断向后移动的
  14.             for (j=i-h; j>=0 && temp < a[j]; j-=h)   //取分组
  15.             {   
  16.                 a[j+h] = a[j];   //a[i]移到后面
  17.             }   
  18.             a[j+h] = temp;   
  19.         }   
  20.     }       
  21.   
  22. int main(void)  
  23. {  
  24.     int arr[]={1,5,2,4,3,8,6,7,9};  
  25.     int count=sizeof(arr)/sizeof(int);  
  26.       
  27.     Shell_Sort(arr,count);  
  28.   
  29.     int k;  
  30.     for(k=0;k<count;k++)  
  31.     {  
  32.         printf("%d",arr[k]);  
  33.     }  
  34.     return 0;  
  35. }  

 


0 0
原创粉丝点击