东方博宜OJ 1010:数组元素的排序 ← 希尔排序

【题目来源】
https://oj.czos.cn/p/1010

【题目描述】
对数组的元素按从小到大进行排序。

【输入格式】
第一行有一个整数 n(5≤n≤10);
第二行有 n 个整数,每个整数的值在 [0, 10^9]的范围内。

【输出格式】
输出排序后的数组。

【输入样例】
8
1 2 3 6 8 7 4 5

【输出样例】
1 2 3 4 5 6 7 8

【数据范围】
5≤n≤10

【算法分析】
● 希尔排序(Shell's Sort)又称“缩小增量排序”(Diminishing Increment Sort),是插入排序的一种,因D.L.希尔(D.L.Shell)于1959年提出而得名。
● 希尔排序实质上是采用分组插入的方法,先将整个待排序记录序列分割成几组,从而减少参与直接插入排序的数据量,然后对每组分别进行直接插入排序。之后增加每组的数据量,重新分组。这样当经过几次分组排序后,整个序列中的记录“基本有序”时,再对全体记录进行一次直接插入排序。
● 希尔排序每组采用的是直接插入排序算法,所以把本题的直接插入排序算法实现,与经典的直接插入排序算法实现,对比如下。

直接插入排序 希尔排序

#include <bits/stdc++.h>
using namespace std;
 
const int N=15;
int a[N];
int n;
 
int main() {
    cin>>n;
    for(int i=1; i<=n; i++) cin>>a[i];
     

    for(int i=1; i<=n; i++) {
        int t=a[i];
        int j=i-1;
        while(j>=0 && a[j]>t) {
            a[j+1]=a[j];
            j--;
        }
        a[j+1]=t;
    }
 



    for(int i=1; i<=n; i++) cout<<a[i]<<" ";
 
    return 0;
}
 
/*
in:
5
6 9 2 7 1
out:
1 2 6 7 9
*/

#include <bits/stdc++.h>
using namespace std;

const int N=15;
int a[N];
int n;

int main() {
    cin>>n;
    for(int i=0; i<n; i++) cin>>a[i];

    int step=n/2;
    while(step) {
        for(int i=step; i<n; i++) {
            int t=a[i];
            int j=i-step;
            while(j>=0 && t<a[j]) {
                a[j+step]=a[j];
                j=j-step;
            }
            a[j+step]=t;
        }
        step=step/2;
    }

 

    for(int i=0; i<n; i++) cout<<a[i]<<" ";

    return 0;

}

/*
in:
5
6 9 2 7 1

out:
1 2 6 7 9
*


【算法代码:
希尔排序

#include <bits/stdc++.h>
using namespace std;

const int N=15;
int a[N];
int n;

int main() {
    cin>>n;
    for(int i=0; i<n; i++) cin>>a[i];

    int step=n/2;
    while(step) {
        for(int i=step; i<n; i++) {
            int t=a[i];
            int j=i-step;
            while(j>=0 && t<a[j]) {
                a[j+step]=a[j];
                j=j-step;
            }
            a[j+step]=t;
        }
        step=step/2;
    }

    for(int i=0; i<n; i++) cout<<a[i]<<" ";

    return 0;
}

/*
in:
5
6 9 2 7 1

out:
1 2 6 7 9
*/




【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/161347829
https://blog.csdn.net/hnjzsyjyj/article/details/161332702
https://blog.csdn.net/hnjzsyjyj/article/details/161346075

posted @ 2026-06-01 14:22  Triwa  阅读(15)  评论(0)    收藏  举报