zoukankan      html  css  js  c++  java
  • 希尔排序

     1 #include <iostream>
     2 #include <cstdlib>
     3 
     4 #define ARR_SIZE 10
     5 
     6 using namespace std;
     7 
     8 void shellshort(int a[]);
     9 void CreateRandArr(int a[]);
    10 void exchange(int *a, int *b);
    11 
    12 int main()
    13 {
    14     int a[ARR_SIZE];
    15     int i;
    16     CreateRandArr(a);
    17     shellshort(a);
    18     cout << "after sort: " << endl;
    19     for(i=0;i<ARR_SIZE;i++)
    20     {
    21         cout << a[i] << ' ' ;
    22     }
    23     
    24     return 0;
    25 }
    26 
    27 /* 记住,希尔排序只是比插入排序多了一层while循环和一个递增序列,最内部的for循环把插入排序的1替换成当前递增量h就行了 */
    28 void shellshort(int a[])
    29 {
    30     int i, j, temp, h=1;
    31     while(h < ARR_SIZE/3)h=h*3 +1;   /* 构造递增序列 */
    32     while(h>=1)
    33     {
    34         for(i=h; i<ARR_SIZE; i++)    /* 外围这个for循环每进行一次相当于对每个间隔为h的序列的第i个元素做排序 */
    35         {
    36             for(j=i; j>=h && a[j]<a[j-h]; j-=h)   /* 注意这里j的条件是j>=h.否则j-h可能取值小于0 */
    37             {
    38                 exchange(&a[j], &a[j-h]);
    39             }
    40         }
    41         h = h/3;   /* 按递增序列逐步缩小h,由递增序列可知最后h一定可以等于1,届时相当于插入排序 */
    42     }
    43     
    44 }
    45 
    46 void CreateRandArr(int a[])
    47 {
    48     int i;
    49     for(i=0;i<ARR_SIZE;i++)
    50     {
    51         a[i] = rand() % 100;
    52         cout <<a[i] << ' ' ; 
    53     }
    54     cout << endl;
    55 }
    56 
    57 void exchange(int *a, int *b)
    58 {
    59     int temp;
    60     temp = *a;
    61     *a = *b;
    62     *b = temp;
    63 }
  • 相关阅读:
    CENTOS7下安装REDIS
    Linux 查看端口状态netstat
    Centos7启动zookeeper无法连接2181端口
    企业信息化之路---集成
    Linux启动/停止/重启Mysql数据库的方法
    详解线程池
    详细的RocketMQ说明
    2021面试题准备~~~
    Https原理详解
    es 常用DSL
  • 原文地址:https://www.cnblogs.com/tan-wm/p/14397482.html
Copyright © 2011-2022 走看看