希尔排序(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;
}
相关推荐
罗湖老棍子13 小时前
Knight Moves(信息学奥赛一本通- P1257)
c++·算法·bfs
小李小李快乐不已14 小时前
哈希表理论基础
数据结构·c++·哈希算法·散列表
AuroraWanderll14 小时前
C++11(二)核心突破:右值引用与移动语义(上)
c语言·数据结构·c++·算法·stl
CoderYanger14 小时前
第 479 场周赛Q1——3769. 二进制反射排序
java·数据结构·算法·leetcode·职场和发展
广府早茶14 小时前
机器人重量
c++·算法
sin_hielo14 小时前
leetcode 1925
数据结构·算法·leetcode
CoderYanger14 小时前
A.每日一题——1925. 统计平方和三元组的数目
java·开发语言·数据结构·算法·leetcode·哈希算法
小白程序员成长日记14 小时前
2025.12.08 力扣每日一题
java·算法·leetcode
XH华14 小时前
数据结构第七章:队列的学习
数据结构
zz07232014 小时前
数据结构 —— 并查集
java·数据结构