都有“快速”两个字,实际上快速选择算法跟快速排序算法的思想完全一样:先分区。也就是分治的思想。快速选择算法的目的就是找到数组中的第K大的数。
我写的快速排序的算法见这里:http://hi.baidu.com/microgrape/blog/item/30b7f88a0166bd1bc9fc7a43.html
可以对比一下下面的快速选择算法的代码。
#include <iostream>
#include <vector>
using namespace std;
//search the kth biggest number
int QuickSelect(vector<int> &a, int left, int right, int k)
{
int pivot = a[ left ];
int i = left;
int j = right;
while( i < j )
{
//NOTE: ">=" not ">"
while ( a[j] >= pivot && i < j )
j--;
a[i] = a[j];
while ( a[i] <= pivot && i < j )
i++;
a[j] = a[i];
}
a[i] = pivot;
//there are i+1 numbers from a[0] to a[i]
if( k < i + 1 )
return QuickSelect( a, left, i - 1 , k);
else if( k > i + 1 )
return QuickSelect( a, i + 1, right, k);
else
return a[i];
}
int main(void)
{
vector<int> a;
//a[] = {4,2,1,7,10,5,3,2};
//the fourth one should be 3.
a.push_back(4);
a.push_back(2);
a.push_back(1);
a.push_back(7);
a.push_back(10);
a.push_back(5);
a.push_back(3);
a.push_back(2);
cout<<QuickSelect(a, 0, a.size() - 1, 4);
}
#include <vector>
using namespace std;
//search the kth biggest number
int QuickSelect(vector<int> &a, int left, int right, int k)
{
int pivot = a[ left ];
int i = left;
int j = right;
while( i < j )
{
//NOTE: ">=" not ">"
while ( a[j] >= pivot && i < j )
j--;
a[i] = a[j];
while ( a[i] <= pivot && i < j )
i++;
a[j] = a[i];
}
a[i] = pivot;
//there are i+1 numbers from a[0] to a[i]
if( k < i + 1 )
return QuickSelect( a, left, i - 1 , k);
else if( k > i + 1 )
return QuickSelect( a, i + 1, right, k);
else
return a[i];
}
int main(void)
{
vector<int> a;
//a[] = {4,2,1,7,10,5,3,2};
//the fourth one should be 3.
a.push_back(4);
a.push_back(2);
a.push_back(1);
a.push_back(7);
a.push_back(10);
a.push_back(5);
a.push_back(3);
a.push_back(2);
cout<<QuickSelect(a, 0, a.size() - 1, 4);
}
我还是采用了最简单的选择枢纽元(或者叫哨兵)的方法,取第一个元素。
例程中是取了第4大的元素,应该为3。