int partition(int a[], int start, int end) {//快排的partition操作
if (start >= end) {
return start;
}
int i = start, j = end;
int tmp = a[start];
while (i < j) {
while (i < j && a[j] >= tmp) {
j--;
}
a[i] = a[j];
while (i < j && a[i] <= tmp) {
i++;
}
a[j] = a[i];
}
a[i] = tmp;
return i;
}
int findMinK(int a[], int start, int end, int k) {
int pivot = partition(a, start, end);
int index = pivot - start + 1;//枢轴所指元素是当前部分的第几小元素
if (index == k) {//如果恰好为第k小,直接返回
return a[pivot];
} else if (index < k) {//如果小于k,则从数组后面返回第k - index小的元素即可
return findMinK(a, pivot + 1, end, k - index);
} else {//如果大于k,则从数组前面返回第k小的元素
return findMinK(a, start, pivot - 1, k);
}
}
int main() {
int b[10] = {10, 3, 8, 9, 6, 5, 2, 4, 7, 1};
cout << findMinK(b, 0, 9, 5) << endl;
return 0;
}
标签:tmp,partition,end,start,找到,元素,int,while,数组
From: https://www.cnblogs.com/zawaludo/p/16807095.html