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

    什么是希尔排序?

    希尔排序是希尔(Donald Shell)于1959年提出的一种排序算法。希尔排序也是一种插入排序,它是简单插入排序经过改进之后的一个更高效的版本,也称为缩小增量排序,同时该算法是冲破O(n2)的第一批算法之一。本文会以图解的方式详细介绍希尔排序的基本思想及其代码实现。

    希尔排序原理:

    希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序;随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止。

    第一种:

    #include<iostream>
    using namespace std;
    
    void shell_sort(int num[], int len)
    {
        for (int nums = len / 2; nums > 0; nums /= 2)            // 将数组进行分组
        {
            for (int i = nums; i < len; i++)                     // 将分组后的数组进行插入排序
            {
                int temp = num[i];
                int j = i;
                while (( j - nums ) >= 0 && num[ j - nums ] > temp)
                {
                    num[j] = num[j - nums];
                    j -= nums;
                }
                num[j] = temp;
            }
        }
        for (int s = 0; s < len; s++)                             // 打印数组
        {
            cout << num[s] << endl;
        }
    }
    int main()
    {
        int num[] = { 1, 2, 6, 7, 4, 5, 3, 8 };
        int len = 8;
        shell_sort(num,len);
        system("pause");
        return 0;
    }

    第二种:

    #include <iostream>
    using namespace std;
    
    void shell_sort(int num[], int len)
    {
        for (int group = len / 2; group > 0; group /= 2)  // 分组
        {
            for (int i = 0; i < group; i++)               // 按组排序
             {
                for (int j = i + group; j < len; j += group) // 组内插入排序
                {
                    if (num[j - group]>num[j])           // 前者大于后者
                    {
                        int temp = num[j];
                        while (j - group >= 0 && temp < num[j - group])
                        {
                            num[j] = num[j - group];    // 将前者的值赋给后者
                            j -= group;
                        }
                        num[j] = temp;                  // 将后者的值赋给前者
                    }
                }
            }
        }
        for (int i = 0; i < len; i++)
        {
            cout << num[i] << endl;
        }
    }
    
    int main()
    {
        int num[] = { 2, 4, 7, 1, 6, 0, 8, 3, 5 };
        int len = 9;
        shell_sort(num, len);
        system("pause");
        return 0;
    }

    第一种方法:是将第一组内的数组进行插入排序,然后再将第二组内的数组进行插入排序,然后再将第三组.........

    第二种方法:是按照组进行排序,以组为单位,处理完一组在处理第二组......

  • 相关阅读:
    pymssql连接Azure SQL Database
    Python升级后ssl模块不可用问题解决和浅析
    CentOS 7升级Python到3.6.6后yum出错问题解决总结
    Python监控SQL Server数据库服务器磁盘使用情况
    fastjason常用方法
    类型擦除真的能完全擦除一切信息吗?java 泛型揭秘
    spring boot打包成war包的页面该放到哪里?
    为什么delete后磁盘空间没有释放而truncate会释放?
    leetcode 977. Squares of a Sorted Array
    leetcode 844. Backspace String Compare
  • 原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/10654931.html
Copyright © 2011-2022 走看看