原题链接:
洛谷 P1177https://www.luogu.com.cn/problem/P1177思路不必多说
代码
#include <iostream>
using namespace std;
const int N = 100010;
int q[N];
void quick_sort(int q[], int l, int r) {
if (l >= r)return;
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]);
}
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] << " ";
return 0;
}
原题链接:
洛谷 P1923https://www.luogu.com.cn/problem/P1923解题思路:
快速排序的过程中可以省略部分排序
代码
#include <iostream>
using namespace std;
const int N = 5000000+100;
int q[N];
int quick_sort(int l, int r, int k) {
if (l >= r)return q[l+1];
int i = l - 1, j = r + 1, x = q[r+((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 tmp=j-l+1;
if (tmp >= k)return quick_sort(l,j, k);
else return quick_sort(j + 1, r,k - tmp);
}
int main() {
ios::sync_with_stdio(false);
int n, k;
scanf("%d %d",&n,&k);
for (register int i = 0; i < n; ++i)scanf("%d",&q[i]);
printf("%d",quick_sort(0,n-1,k));
return 0;
}