自己写的快速排序只能拿60分,求助
查看原帖
自己写的快速排序只能拿60分,求助
1019606
KouMoSir楼主2023/7/6 16:12

用了随机选择基准,快读 代码如下:

#include<iostream>
#include<cstdlib>
#include<cctype>
#include<iomanip>
using namespace std;
const int N = 1e5 + 5;
int n, list[N];
int read() {
    int s = 0; char ch = getchar();
    while (!isdigit(ch))ch = getchar();
    while (isdigit(ch)) {
        s = (s << 1) + (s << 3) + (ch ^ 48);
        ch = getchar();
    }
    return s;
}
void qs(int x, int y) {
    int l = x, r = y;
    if (l >= r)return;
    int pi = rand() % (y - x + 1) + x;
    int p = list[pi];
    swap(list[pi], list[r]);
    r--;
    while (l < r) {
        while (l < r && list[l] < p)l++;
        while (l < r && list[r] >= p)r--;
        swap(list[l], list[r]);
    }
    if (list[l] > p)swap(list[l], list[y]);
    else l++;
    qs(x, l - 1);
    qs(r + 1, y);
}
int main() {
    n = read();
    for (int i = 0; i < n; i++)list[i] = read();
    qs(0, n - 1);
    for (int i = 0; i < n; i++)cout << list[i] << " ";
}
2023/7/6 16:12
加载中...