快排+二分
int getpart(int a[],int low,int high){
if (low>high)
{
return -1;
}
int low_t = low;
int high_t = high;
int key = a[low];
while (low < high)
{
while(low < high && a[high] >= key)
{
high--;
}
if (low<high)
{
a[low++] = a[high];
}
while(low < high && a[low] <= key)
{
low++;
}
if (low<high)
{
a[high--] = a[low];
}
}
a[low] = key; //中轴
return low;
}
int getKnum(int a[],int length,int k){
if (length==0 || k>length)
{
return -1;
}
int start = 0;
int end = length - 1;
int index = getpart(a,start,end);
while (index != k-1)
{
//中轴在目的元素的左边
if (index > k-1)
{
end = index - 1;
index = getpart(a,start,end);
}
else//中轴在目的元素的右边
{
start = index + 1;
index = getpart(a,start,end);
}
}
return a[index];
}
void main(){
int a[] = {5,1,2,6,4,3,9,8,7,10};
int k = 10;
int len = sizeof (a)/4;
int r = getKnum(a,len,k);
printf("%d",r);
while(1);
}
最小的K个数,不按排序输出
//不按顺序
int getKnums(int a[],int length,int k){
if (length==0 || k>length)
{
return -1;
}
int start = 0;
int end = length - 1;
int index = getpart(a,start,end);
while (index != k-1)
{
//中轴在目的元素的左边
if (index > k-1)
{
end = index - 1;
index = getpart(a,start,end);
}
else//中轴在目的元素的右边
{
start = index + 1;
index = getpart(a,start,end);
}
}
for (int i=0;i<k;i++)
{
printf("%d ",a[i]);
}
return a[index];
}