zoukankan      html  css  js  c++  java
  • C语言实例解析精粹学习笔记——43(希尔排序)

    实例说明:

      用希尔排序方法对数组进行排序。由于书中更关注的实例,对于原理来说有一定的解释,但是对于第一次接触的人来说可能略微有些简略。自己在草稿纸上画了好久,后来发现网上有好多很漂亮的原理图。

      下面将原书中的程序附上(主函数里的程序略有差异)

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 #define MAX 256
     5 int R[MAX];
     6 
     7 void ShellPass(int d, int n)
     8 {
     9     //希尔排序中的一趟排序,d为当前增量
    10     int i,j;
    11     for(i=d+1; i<=n; i++)    //将R[d+1...n]分别插入各组当前的有序区。
    12     {
    13         if(R[i] < R[i-d])
    14         {
    15             R[0]=R[i]; j=i-d;   //R[0]只是暂存单元,不是哨兵。
    16             do{                 //查找R[i]的插入位置
    17                 R[j+d] = R[j];  //后移记录
    18                 j = j-d;        //查找前一记录
    19             }while(j>0 && R[0]<R[j]);
    20             R[j+d] = R[0];      //插入R[i]到正确的位置上
    21         }
    22     }
    23 }
    24 
    25 void ShellSort(int n)
    26 {
    27     int increment = n;         //增量初值
    28     do{
    29         increment = increment/3 +1;  //求下一增量
    30         ShellPass(increment, n);
    31     }while(increment > 1);
    32 }
    33 
    34 int main()
    35 {
    36     int n;
    37 
    38 
    39     printf("Please input total element number of the sequence:");
    40     scanf("%d",&n);
    41 
    42     if(n > MAX)
    43     {
    44         printf("ERROR! There are too many elements!");
    45         return 0;
    46     }
    47     else if(n <= 0)
    48     {
    49         printf("ERROR!");
    50         return 0;
    51     }
    52 
    53     printf("Please input the element one by one:
    ");
    54     for(int i=1; i <= n; i++)
    55     {
    56         scanf("%d", &R[i]);
    57     }
    58 
    59     printf("The sequence you input is :");
    60     for(int i=1; i<=n; i++)
    61         printf("%4d", R[i]);
    62 
    63     ShellSort(n);
    64     printf("
    The sequence after shell sort is:");
    65     for(int i=1; i<=n; i++)
    66         printf("%4d", R[i]);
    67 
    68     return 0;
    69 }
  • 相关阅读:
    《精通CSS网页布局》读书报告 ----2016-12-5补充
    定位始终居中显示
    IntelliJ idea的使用
    模拟发送http请求
    知识漏洞
    【NX二次开发】Block UI 半径尺寸(沿曲线的位置)
    【NX二次开发】Block UI 角度尺寸
    【NX二次开发】Block UI 线性尺寸
    【NX二次开发】Block UI 表达式
    【NX二次开发】Block UI 整形
  • 原文地址:https://www.cnblogs.com/llccbb1/p/10756857.html
Copyright © 2011-2022 走看看