785. 快速排序

AcWing 785. 快速排序

快排边界问题分析与证明

给定你一个长度为 n 的整数数列。

请你使用快速排序对这个数列按照从小到大进行排序。

并将排好序的数列按顺序输出。

输入格式
输入共两行,第一行包含整数 n。

第二行包含 n 个整数(所有整数均在 1∼109 范围内),表示整个数列。

输出格式
输出共一行,包含 n 个整数,表示排好序的数列。

数据范围
1≤n≤100000
输入样例:
5
3 1 2 4 5
输出样例:
1 2 3 4 5

注意:

注意本题数据已加强。
快速排序过程中,如果每次取区间起点或者终点作为分界点,则会超时。
分界点换成随机值,或者区间中点即可。

AC:

#include <cstdio>
#include <iostream>

using namespace std;

//# define N 100005
const int N = 100005;

int num[N];

void quickSort(int left, int right)
{
    if (left >= right) return;
    int i = left - 1, j = right + 1;//边界往左往右扩一位
    int key = num[i+j>>1];
    while (i < j)
    {
        do i++; while (num[i] < key);
        do j--; while (num[j] > key);
        if (i < j) swap(num[i], num[j]);
    }
    /*
    用i则不能取到左边界,把x取值改成向上取整
    用j则不能取到右边界,把x取值改成向下取整
    取到边界会导致递归死循环
    */
    quickSort(left, j);//或i-1
    quickSort(j+1, right);//i
    return;
}

int main()
{
    int n;
    cin>>n;
    for (int i = 0; i < n; i++)
        scanf("%d",&num[i]);

    quickSort(0,n-1);

    for (int i = 0; i < n; i++)
        cout<<num[i]<<' ';
    cout<<endl;

    return 0;
}

超时:

#include <cstdio>
#include <iostream>

using namespace std;

//# define N 100005
const int N = 100005;

long long num[N];

void quickSort(int left, int right)
{
    if (left>=right)return;

    int i = left, j = right;
    long long key = num[i];
    while (i < j)
    {
        while (i < j && num[j] > key) j--;
        if (i < j) num[i++] = num[j];

        while (i < j && num[i] < key) i++;
        if (i < j) num[j--] = num[i];
    }
    num[i] = key;

    quickSort(left, i-1);
    quickSort(i+1, right);
    return;
}

int main()
{
    int n;
    cin>>n;
    for (int i = 0; i < n; i++)
        scanf("%lld",&num[i]);

    quickSort(0,n-1);

    for (int i = 0; i < n; i++)
        cout<<num[i]<<' ';
    cout<<endl;

    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值