目录
10.3 查找第 k 小元素!
和快速排序相近。不同的是,在“递归”这一阶段只需对“有第 k 小数据”的一部分进行排序,另一部分就不用管了。理想情况下,该算法的复杂度能达到线性水平。
int part(int *a, int start, int end)
{
int low=start, high=end;
int temp, check=a[start];
do
{
while (a[high]>=check&&low<high)
high--;
if (a[high]<check)
temp=a[high], a[high]=a[low], a[low]=temp;
while (a[low]<=check&&low<high)
low++;
if (a[low]>check)
temp=a[high], a[high]=a[low], a[low]=temp;
}
while (low!=high);
a[low]=check;
return low;
}
int find(int *a, int start, int end, int k)
{
if (start==end)
return a[start];
int p = part(a, start, end);
int q = p-start+1; // 计算p位置的“排名”
// 只对包含第k小元素的部分进行查找和排序。
if (k <= q)
return find(a, start, p, k);
else
return find(a, p+1, end, k-q);
}
如果 k 不太大,可以用堆(优先队列)解决。