C++实现直接插入排序、希尔排序

630阅读 0评论2013-07-08 double_lq
分类:C/C++

数据结构中所讲解的集中排序如下:
 
  
直接插入排序实现如下:

   
  1. //1、直接插入排序
  2. #include
    using namespace std;


    #define MAXSIZE 20
  3. void InsertSort(int r[],int n)
  4. {
  5.     int i,j;
  6.     for(i=2;i<=n;i++)
  7.     {
  8.      if(r[i]<r[i-1])
  9.         {
  10.          r[0]=r[i];
  11.             r[i]=r[i-1];
  12.             for(j=i-2;r[0]<r[j];--j)
  13.                 r[j+1]=r[j];
  14.             r[j+1]=r[0];
  15.         }
  16.     }
  17. }


  1. int main()
  2. {
  3.     int i,n;
  4.     int r[MAXSIZE];
  5.     cout<<"please input the total count you want to sort:"<<endl;
  6.     cin>>n;
  7.     cout<<"please input the numbers:"<<endl;
  8.     for(i=1;i<=n;i++)
  9.     {
  10.         cin>>r[i];
  11.     }

  12.     InsertSort(r,n);
  13.     for(i=1;i<=n;i++)
  14.      cout<<r[i]<<" ";
  15.     return 0;

  16. }



  1. //希尔排序
  2. #include<iostream>
  3. using namespace std;

  4. #define MAXSIZE 20
  5. #define MAXNUM 5


  6. void ShellInsert(int r[],int dk,int n)
  7. {
  8.     int i,j;
  9.     for(i=dk+1;i<=n;i++)
  10.     {
  11.      if(r[i]<r[i-dk])
  12.         {
  13.          r[0]=r[i];
  14.             for(j=i-dk;j>0&&r[0]<r[j];j-=dk)
  15.                 r[j+dk]=r[j];
  16.             r[j+dk]=r[0];
  17.         }
  18.     }
  19. }

  20. void ShellSort(int r[],int dlta[],int t,int n)
  21. {
  22.     int k;
  23.     for(k=0;k<t;k++)
  24.         ShellInsert(r,dlta[k],n);
  25. }


  26. int main()
  27. {
  28.     int i,n,m;
  29.     int r[MAXSIZE],dlta[MAXNUM];
  30.     cout<<"please input the total count you want to sort:"<<endl;
  31.     cin>>n;
  32.     cout<<"please input the numbers:"<<endl;
  33.     for(i=1;i<=n;i++)
  34.     {
  35.         cin>>r[i];
  36.     }

  37.     cout<<"please input the Dk numbers:"<<endl; //  增量数目 3
  38.     cin>>m;
  39.     cout<<"please input the kd values:"<<endl;  //增量值  5,3,1
  40.     for(i=0;i<m;i++)
  41.         cin>>dlta[i];
  42.     ShellSort(r,dlta,m,n);
  43.     for(i=1;i<=n;i++)
  44.      cout<<r[i]<<" ";
  45.     return 0;

  46. }











上一篇:c++中解析for循环
下一篇:c语言strncpy函数