1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| #include <stdio.h> #define MAXN 10
int search(int a[], int n, int k); int main() { int a[MAXN] = {3, 3, 1, 3, 3, 0, 0, 2, 1, 3}, n; printf("输入n值:\n"); scanf("%d", &n); printf("%d \n", search(a, 10, n)); for (int i = 0; i < 10; i++) { printf("%d ", a[i]); } printf("\n"); return 0; }
int search(int a[], int n, int k) { int low, high, i, j, t; k--; low = 0; high = n - 1; do { i = low; j = high; t = a[low];
do { while (i < j && t <= a[j]) { j--; } a[i] = a[j]; while (i < j && t > a[i]) { i++; } a[j] = a[i]; } while (i < j);
if (i == k) { return t; } else if (i < k) { low = i + 1; } else { high = i - 1; } } while (low < high); return a[low]; }
|