希尔排序(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;
}
相关推荐
什巳2 小时前
JAVA练习306- 翻转二叉树
java·数据结构·算法·leetcode
smj2302_796826522 小时前
解决leetcode第3989题网格中保持一致的最大列数
python·算法·leetcode
巧克力男孩dd3 小时前
Python超典型练习题(第一次作业)
开发语言·python·算法
爱刷碗的苏泓舒3 小时前
平方根信息滤波:矩阵推导及 GNSS 参数估计应用
线性代数·算法·矩阵·gnss·参数估计·测量平差·平方根信息滤波
想做小南娘,发现自己是女生喵4 小时前
第 2 章 顺序表和 vector
java·数据结构·算法
艾醒5 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
雪碧聊技术5 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo5 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花5 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活
Reart6 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法