voidquick_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]);
#include<iostream> #include<algorithm> #include<cmath> #include<cstdio> #include<cstring> #include<stack> usingnamespace std; constint N = 1e6 + 9; int a[N]; intquick(int l, int r, int k) { if (l == r) return a[l]; int x = a[l], i = l - 1, j = r + 1; while (i < j) {
while (a[++i] < x);
while (a[--j] > x); if (i < j) swap(a[i], a[j]); } int sl = j - l + 1; if (sl >= k) returnquick(l, j, k); else returnquick(j + 1, r, k - sl); } intmain() { int n, k; cin >> n >> k; for (int i = 0; i < n; i++) scanf("%d", a + i); cout << quick(0, n - 1, k) << endl; return0; }
归并排序
1 2 3 4 5 6 7 8 9 10 11 12 13 14
voidmerge_sort(int q[], int l, int r) { if (l >= r) return; int mid = l + r >> 1; merge_sort(q, l, mid); merge_sort(q, mid + 1, r); int k = 0, i = l, j = mid + 1; while (i <= mid && j <= r) if (q[i] <= q[j]) tem[k++] = q[i++]; else tem[k++] = q[j++]; while (i <= mid) tem[k++] = q[i++]; while (j <= r) tem[k++] = q[j++]; for (int i = l,j =0; i <= r; i++, j++) q[i] = tem[j]; }