AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

插入排序&希尔排序

作者: 作者的头像   Shevon ,  2024-12-18 22:52:47 ,  所有人可见 ,  阅读 5


0


直接插入排序

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

const int N = 1010;

int a[N];
int n;

void InsertSort()
{
    // 要插入的数为end+1
    for (int i = 0; i < n - 1; i++)
    {
        int end = i;
        int key = a[end + 1];
        while (end >= 0 && a[end] > key) // a[]覆盖后移并end前移过程
        {
            a[end + 1] = a[end];
            end--;
        }
        a[end + 1] = key; // 当前end比key小,直接在end+1处插入key
    }
}

int main()
{
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    InsertSort();
    for (int i = 0; i < n; i++)
    {
        cout << a[i] << ' ';
    }
    return 0;
}

希尔排序

#include <bits/stdc++.h>
using namespace std;
const int N = 1000;

int a[N];
int n;

void ShellSort()
{
    int gap = n;
    for (int g = gap / 2; g >= 1; g /= 2)
    {
        for (int k = 0; k < g; k++)
        {
            for (int j = k + g; j < n; j += g)
            {
                int end = j - g;
                int key = a[end + g];
                while (end >= 0 && a[end] < key)
                {
                    a[end + g] = a[end];
                    end -= g;
                }
                a[end + g] = key;
            }
        }
        for (int x = 0; x < n; x++)
        {
            cout << a[x];
            if (x != n - 1)
                cout << ' ';
        }
        cout << endl;
    }
}

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        cin >> n;
        for (int i = 0; i < n; i++)
        {
            cin >> a[i];
        }
        ShellSort();
        if (t != 0)
            cout << endl;
    }
    return 0;
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息