希尔排序(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;
}
相关推荐
池央1 天前
贪心算法-最大数
算法·贪心算法
Yvonne爱编码1 天前
JAVA数据结构 DAY1-集合和时空复杂度
java·数据结构·python
iAkuya1 天前
(leetcode)力扣100 57电话号码的字母组合(回溯)
算法·leetcode·深度优先
m0_736919101 天前
模板元编程性能分析
开发语言·c++·算法
pen-ai1 天前
【YOLO系列】 YOLOv1 目标检测算法原理详解
算法·yolo·目标检测
2301_765703141 天前
C++中的职责链模式实战
开发语言·c++·算法
StandbyTime1 天前
《算法笔记》学习记录-第一章
c++·算法·算法笔记
近津薪荼1 天前
优选算法——双指针8(单调性)
数据结构·c++·学习·算法
松☆1 天前
Dart 中的常用数据类型详解(含 String、数字类型、List、Map 与 dynamic) ------(2)
数据结构·list
格林威1 天前
Baumer相机铆钉安装状态检测:判断铆接是否到位的 5 个核心算法,附 OpenCV+Halcon 的实战代码!
人工智能·opencv·算法·计算机视觉·视觉检测·工业相机·堡盟相机