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;
    }

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

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

  • 相关阅读:
    d3js 获取元素以及设置属性
    javascript 转义函数
    es6 对象浅拷贝的2种方法
    SwitchyOmega 代理设置
    table 设置边框
    Highcharts 配置选项详细说明
    windows环境下生成ssh keys
    vue 给组件绑定原生事件
    Vue 字面量语法 vs 动态语法
    Vue 2.0 v-for 响应式key, index及item.id参数对v-bind:key值造成差异研究
  • 原文地址:https://www.cnblogs.com/zhuifeng-mayi/p/10654931.html
Copyright © 2011-2022 走看看