希尔排序(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;
}
相关推荐
while(1){yan}22 分钟前
数据结构之链表
数据结构·链表
Han.miracle2 小时前
数据结构——二叉树的从前序与中序遍历序列构造二叉树
java·数据结构·学习·算法·leetcode
mit6.8244 小时前
前后缀分解
算法
独自破碎E5 小时前
判断链表是否为回文
数据结构·链表
你好,我叫C小白5 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
寂静山林7 小时前
UVa 10228 A Star not a Tree?
算法
Neverfadeaway7 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
Madison-No78 小时前
【C++】探秘vector的底层实现
java·c++·算法
Swift社区8 小时前
LeetCode 401 - 二进制手表
算法·leetcode·ssh
派大星爱吃猫8 小时前
顺序表算法题(LeetCode)
算法·leetcode·职场和发展