查找数组的第k小元素
2018-12-04 本文已影响2人
飞白非白
int findPivorIdx(int A[], int k, int low, int high) {
int pivor = A[low];
while (low<high)
{
while (A[high]>=pivor && low<high)
{
high--;
}
A[low] = A[high];
while (A[low]<pivor && low<high)
{
low++;
}
A[high] = A[low];
}
A[low] = pivor;
return low;
}
int findKMin(int A[],int k, int low, int high) {
if (low<high) // 继续查找
{
int pId = findPivorIdx(A,k,low,high);
if ((pId+1)==k) // 找到了
{
return A[pId];
}else if((pId+1)<k) { // 还在右边
return findKMin(A,k,pId+1,high); // 对右边递归
}else if((pId+1)>k){
return findKMin(A,k,low,pId-1); // 对左边递归
}
}
else { // 返回low
return A[low];
}
}