分治法求第k小元素
/*Name: 第k小元素Copyright: Author: Date: 13-04-17 15:28Description: 求一列數(shù)中的第k小元素,利用分治的策略進(jìn)行遞歸求解。模仿快速排序法的思路,只不過每次只遞歸處理第k小元素所在的序列。要注意每次都應(yīng)該減少搜索的范圍,避免因?yàn)殡S機(jī)數(shù)不隨機(jī)而導(dǎo)致的死循環(huán)
*/
#include<iostream>
#include<cmath>
#include<ctime>using namespace std;int Partition(int A[], int low, int high);
int SelectK(int A[], int low, int high, int k);
void Swap(int &a, int &b);int main()
{const int N = 200;int A[N] = {0};for (int i=0; i<N; i++){A[i] = rand() % 1000;}for (int i=0; i<N; i++){cout << A[i] << " ";}cout << endl;int k = 5;cout << SelectK(A, 0, N-1, k) << endl;for (int i=0; i<N; i++){cout << A[i] << " ";}cout << endl;system("pause");return 0;
}void Swap(int &a, int &b)
{int temp = a;a = b;b = temp;
}int SelectK(int A[], int low, int high, int k)
{if (low == high)return A[low];int mid = Partition(A, low, high);int leftLen = mid - low + 1;if (k == leftLen)return A[mid];else if (k < leftLen) //要考慮隨機(jī)數(shù)不隨機(jī)的特殊情形,避免進(jìn)入死循環(huán) return SelectK(A, low, mid-1, k);elsereturn SelectK(A, mid+1, high, k-leftLen);
}int Partition(int A[], int low, int high)
{srand((unsigned)time(NULL)); //生成隨機(jī)數(shù)int i, j = rand() % (high - low) + low; Swap(A[low], A[j]); //把樞紐元素置換到最左端 int x = A[low];i = low; j = high + 1;while (true){while (A[++i] <= x && i < high) ;while (A[--j] > x) ;if (i >= j)break;Swap(A[i], A[j]);} Swap(A[low], A[j]); //把樞紐元素置換到它該處的位置return j;
}
總結(jié)
- 上一篇: 京瓷6525_京瓷6525复印机报价 京
- 下一篇: 高维数据中特征筛选方法的思考总结——单变