第一讲:基础算法
785. 快速排序
#include <iostream>
using namespace std;
const int N = 1000010;
int q[N];
void quick_sort(int q[], int l, int r) {
if (l >= r) return ;
int x = q[(l + r) / 2], i = l - 1, j = r + 1;
while (i < j) {
do i++;while (q[i] < x);
do j--;while (q[j] > x);
if (i < j) swap(q[i], q[j]);
}
quick_sort(q, l, j);
quick_sort(q, j + 1, r);
}
int main() {
int n;
cin >> n;
for (int i = 0; i < n; ++i) cin >> q[i];
quick_sort(q, 0, n - 1);
for (int i = 0; i < n; ++i) cout << q[i] << " ";
puts("");
return 0;
}
786. 第k个数
#include <iostream>
using namespace std;
const int N = 100010;
int n, k, q[N];
int quick_sort(int l, int r, int k) {
if (l >= r) return q[l];
int i = l - 1, j = r + 1, x = q[l + r >> 1];
while (i < j) {
do i ++ ; while (q[i] < x);
do j -- ; while (q[j] > x);
if (i < j) swap(q[i], q[j]);
}
int sl = j - l + 1;
if (k <= sl) return quick_sort(l, j, k);
return quick_sort(j + 1, r, k - sl);
}
int main() {
scanf("%d%d", &n, &k);
for (int i = 0; i < n; ++i) scanf("%d", &q[i]);
cout << quick_sort(0, n - 1, k) << endl;
}
原文地址:https://www.cnblogs.com/clown9804/p/12628754.html
时间: 2024-10-09 00:10:41