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;
}