使用随机数选取数,但第五个测试点还是超时了。
#include <iostream>
#include <cstring>
#include <ctime>
#define MAXN 100010
using namespace std;
int a[MAXN];
void swap(int num[], int i, int j) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
void qSort(int a[], int low, int high) {
if (low >= high) return;
srand(time(0));
int i = low, j = high;
int randPivot = rand() % (high - low + 1) + low;
int key = a[randPivot];
swap(a, low, randPivot);
while (i < j) {
while (i < j && a[j] >= key) --j;
while (i < j && a[i] <= key) ++i;
swap(a, i, j);
}
swap(a, i, low);
qSort(a, i + 1, high);
qSort(a, low, i - 1);
}
int main() {
int n;
cin >> n;
for(int i = 1; i <= n; ++i) {
cin >> a[i];
}
qSort(a, 1, n);
for(int i = 1; i < n; ++i) {
cout << a[i] << " ";
}
cout << a[n];
return 0;
}