cxfans
9/9/2019 - 2:08 AM

p304-5

p304-5

int kth_elem(int a[], int low, int high, int k) {
    int pivot = a[low], i = low, j = high;
    while (i < j) {
        while (i < j && a[j] >= pivot) j++;
        a[i] = a[j];
        while (i < j && a[i] <= pivot) i++;
        a[j] = a[i];
    }
    a[i] = pivot;
    if (i == k) return a[i];
    else if (i > k) return kth_elem(a, low, i - 1, k);
    else return kth_elem(a, i + 1, high, k - i);
}