快速SELECT算法

来源:互联网 发布:网络盒子怎么连接电视 编辑:程序博客网 时间:2024/05/17 13:06
#include <iostream>#include <algorithm>using namespace std;int a[] = {4, 3, 6, 8, 10, 9, 2, 5, 7, 1};void select(int a[], int lhs, int rhs, int k){if(lhs > rhs || k < 0)return;int i = lhs, j = rhs, pivot = a[lhs];while(i < j){while(a[j] >= pivot && i < j)j--;while(a[i] <= pivot && i < j)i++;if(i < j){int t = a[i];a[i] = a[j];a[j] = t;}}if(i == j){a[lhs] = a[i];a[i] = pivot;for(int l = 0; l < 10; ++l)cout << a[l] << " ";cout << endl;if(i-lhs> k)select(a, lhs, i - 1, k);else if(i-lhs < k)select(a, i + 1, rhs, k - i + lhs - 1);elsereturn;}return;}int main(void){int k = 7;//7select(a, 0, 9, k);for(int i = 0; i < k; ++i)cout << a[i] << " ";cout << endl;return 0;}

0 0