zoukankan      html  css  js  c++  java
  • 插入排序及升级版希尔排序

     1 //直接快插法,最好情况每次插入数据就在最后时间复杂度为O(n),最坏情况为每次插入数据为最小,
     2 //每次移动最大次数及时间复杂度为O(n2)
     3 void InsertSort(int array[], int n)
     4 {
     5     int i, j;
     6     for (i = 1; i < n; ++i)//从第二个数据开始,默认第一个数据已经有序
     7     {
     8         int tenp = array[i];//将要插入数据先寄存
     9         j = i;
    10         while (j >0 && tenp < array[j-1])
    11         {
    12             array[j] = array[j-1];//数据后移
    13             --j;
    14         }
    15         array[j] = tenp;//插入到正确位置
    16     }
    17 }
    18 
    19 //插入排序升级版希尔排序
    20 void ShellSort(int array[], int n)  
    21 {
    22     /*//大话数据结构示例
    23     int i, j, temp;
    24     int increment = n;
    25     do {
    26         increment = increment / 3 + 1;
    27         for (i = increment + 1; i <= n; ++i)
    28         {
    29             if (array[i] < array[i - increment])
    30             {
    31                 temp = array[i];
    32                 j = i - increment;
    33                 while(j > 0 && array[j] > temp)
    34                 {
    35                     array[j + increment] = array[j];
    36                     j -= increment;              
    37                 }
    38                 array[j + increment] = temp;
    39             }
    40         }
    41     } while (increment > 1);*/
    42 
    43     int i, j;
    44     int step = n;
    45     for (step = step / 2; step > 0; step = step / 2)  //这里的step步长是根据元素个数这种情况定义的
    46     {        
    47         for (i = step; i < n; ++i)
    48         {
    49             if (array[i] < array[i - step])
    50             {
    51                 int temp = array[i]; //把数组下标i的值放到temp中
    52                 j = i;
    53                 while (j >= step && array[j - step] > temp)
    54                 {
    55                     array[j] = array[j - step]; //把大的值往后插入
    56                     j -= step;
    57                 }
    58                 array[j] = temp; //把小的值往前插入
    59             }           
    60         }       
    61     }
    62 }
    63 //希尔排序的时间复杂取决于增量序列,但是它已经突破了为O(n2);
  • 相关阅读:
    一种新的数据类型Symbol
    var/let/const的区别
    Vue-cli脚手架 安装 并创建项目--命令
    命令
    git版本控制入门--码云
    闲鱼hu超赞,有赞必回,24小时在线!咸鱼互赞超赞留言评
    咸鱼互粉互赞必回 有没有宝贝要的_咸鱼吧
    闲鱼互赞群
    拍摄者能在抖音教学中学会什么
    影响抖音推荐机制的因素和上热门
  • 原文地址:https://www.cnblogs.com/dhhu007/p/13182080.html
Copyright © 2011-2022 走看看