希尔排序(Shell_sort)

希尔排序常用于插入排序的数据预处理,用于提升插入排序的大数据处理速度

将插入排序的函数改为n递增即可使用希尔排序

间隔为n的插入排序:

将i初始值改为0,然后j循环所有的1改为n即可

cpp 复制代码
void Insertion_sort(int *arr,int size,int n)
{
    int i,j;
    for(i = 0;i < size;++i)//第一个元素不用排序
    {
        int t = arr[i];
        for(j = i-n;j >= 0 && arr[j] > t;j-=n)
        {
            arr[j+n] = arr[j];//直接覆盖,速度更快(将前一个覆盖到后面)
        }
        arr[j+n] = t;//因为是覆盖,所以要最后赋值
    }
}

复制代码
10
3 1 2 8 7 5 9 4 6 0

先以5为间隔

排序为

cpp 复制代码
0 1 2 4 3 5 8 6 9 7

然后以2为间隔

cpp 复制代码
0 1 2 4 3 5 8 6 9 7

最后以1为间隔

cpp 复制代码
0 1 2 3 4 5 6 7 8 9

希尔排序虽然看着多了跟多步,但是在大数据的情况下要比单纯的插入排序快上不少

c++代码如下:

cpp 复制代码
#include <bits/stdc++.h>

using namespace std;

void print_arr(int *arr,int size)
{
    for(int i = 0;i < size;++i)
    {
        cout << arr[i];
        if(i != size-1)
        {
            cout << " ";
        }
    }
}

void Insertion_sort(int *arr,int size,int n)
{
    int i,j;
    for(i = 0;i < size;++i)//第一个元素不用排序
    {
        int t = arr[i];
        for(j = i-n;j >= 0 && arr[j] > t;j-=n)
        {
            arr[j+n] = arr[j];//直接覆盖,速度更快(将前一个覆盖到后面)
        }
        arr[j+n] = t;//因为是覆盖,所以要最后赋值
    }
}

void Shell_sort(int *a,int length)
{
    int n = length/2;
    while(n >= 1)
    {
        Insertion_sort(a,length,n);
        n /= 2;
    }
}

int main()
{
    int n;
    cin >> n;
    int arr[n];
    for(int i = 0;i < n;++i)
    {
        cin >> arr[i];
    }
    Shell_sort(arr,n);
    print_arr(arr,n);
    cout << endl;
}
相关推荐
测试仪器廖生135902563857 分钟前
罗德与施瓦茨 FSP13频谱分析仪FSP30
网络·人工智能·算法
happymaker06269 分钟前
LeetCodeHot100——560.和为K的子数组
算法
dtq042426 分钟前
C语言刷题数组5,6(求平均值,求最大值)
c语言·数据结构·算法
郭梧悠38 分钟前
Hash算法入门Hash冲突解决方案
算法·哈希算法
洛水水1 小时前
【力扣100题】81.寻找两个正序数组的中位数
数据结构·算法·leetcode
happymaker06262 小时前
LeetCodeHot100——155.最小栈
算法
洛水水2 小时前
【力扣100题】85.每日温度
算法·leetcode·职场和发展
Coder-magician2 小时前
《代码随想录》刷题打卡day15:二叉树part05
数据结构·c++·算法
Kurisu_红莉栖2 小时前
力扣56合并区间
算法·leetcode
Darling噜啦啦2 小时前
二叉树与递归算法实战:从树结构到 LeetCode 爬楼梯,一文吃透前端数据结构与递归思维
前端·javascript·数据结构