#include <iostream>
using namespace std;
int partion(int* arr, int left, int right){
int i = left, j = right, x = arr[i];
while (i < j){
while (i < j && x <= arr[j]) --j;
if (i < j) arr[i++] = arr[j];
while (i < j && x > arr[i]) ++i;
if (i < j) arr[j--] = arr[i];
}
arr[i] = x;
return i;
}
int select(int*arr, int left, int right, int index){
int n = partion(arr, left, right);
if (n == index) return arr[n];
if (index < n) select(arr, left, n - 1, index);
else select(arr, n + 1, right, index);
}
int main(){
int arr[] = { 7,2,5,4,3,6,1,8,0 };
cout << select(arr, 0, 8, 5) << endl;
return 0;
}
期待为线性时间的选择算法
最新推荐文章于 2021-09-25 14:04:51 发布