zoukankan      html  css  js  c++  java
  • Shell排序 C&&C++

    Shell排序
     
    Shell排序是大量数据需要排序时,更为高效的插入排序。它的算法思想基于插入排序的算法思想
    流程:
    (1)将n个元素数组分成n/2个数字序列,第一个数据和第n/2个数据为一对,等等,以此类推
    (2)一次循环使每一个数对排列好顺序
    (3)变成n/4个数对,再次排序。
    (4)不断重复上述过程,随着序列减少直至最后变为1个,完成排序。
    具体如何怎么排的可以运行代码查看每一步排序。
     
     
     1 #include<iostream>
     2 #include<cstdlib>
     3 #include<ctime>
     4 using namespace std;
     5 void ShellSort(int *a,int len)
     6 {
     7     int x,t,j;
     8     for (int r = len/2; r >=1 ; r/=2)    //外层循环分组
     9     {
    10         for (int i = r; i < len; i++)    
    11         {//内层循环设置一定间距r,分别比较对应元素,当r=1时,这个时候就为插入排序,数组元素数量大时这时效率比插入排序高。
    12             t=a[i];
    13             j=i-r;
    14             while (j>=0&&t<a[j])
    15             {
    16                 a[j+r]=a[j];
    17                 j-=r;
    18             }
    19             a[j+r]=t;
    20             x++;
    21             cout<<"Sort result after "<<x<<" step";              //输出每一步排序结果
    22             for (int k = 0; k < len; k++) cout<<a[k]<<" ";
    23             cout<<endl;
    24         }
    25         
    26     }
    27     
    28 }
    29 int main()
    30 {
    31     srand(time(NULL));
    32     int n;
    33     cout<<"Please cin the size of array:"<<endl; //输入数组的大小
    34     cin>>n;
    35     int a[n];
    36     cout<<"Array before sorting:"<<endl;
    37     for (int i = 0; i < n; i++)            //利用随机数作为数组输入
    38     {
    39         a[i]=rand()/1000;
    40         cout<<a[i]<<" ";
    41     }
    42     cout<<endl;
    43     ShellSort(a,n);
    44     cout<<"Array after sorting:"<<endl;  //输出排序后的数组
    45     for (int i = 0; i < n; i++) cout<<a[i]<<" ";
    46     cout<<endl;
    47     return 0; 
    48     
    49 }
  • 相关阅读:
    四,awk格式化
    printf命令详解
    三,awk变量
    二,awk分隔符
    一,AWK基础
    【leetcode_easy_array】1399. Count Largest Group
    【leetcode_easy_array】1184. Distance Between Bus Stops
    【leetcode_easy_array】1346. Check If N and Its Double Exist
    【leetcode_easy_array】1304. Find N Unique Integers Sum up to Zero
    【leetcode_easy_array】1337. The K Weakest Rows in a Matrix
  • 原文地址:https://www.cnblogs.com/Arthas8086/p/11948888.html
Copyright © 2011-2022 走看看