#include <stdio.h>
/*先给出一个划分函数(快速排序的划分)*/
int partition(int* ar, int left, int right)
{
int i = left;
int j = right;
int tmp = ar[i];
while (i < j)
{
while (i<j && ar[j] > tmp)
{
j--;
}
if (i < j) ar[i] = ar[j];
while (i < j && ar[i] <= tmp)
{
i++;
}
if (i < j) ar[j] = ar[i];
}
ar[i] = tmp;
return i;
}
//递归
int Selectk(int* ar, int left, int right, int k)
{
if (left == right && k == 1)
{
return ar[left];
}
int index = partition(ar, left, right);//index是物理下标
int pos = index - left + 1;//pos是将物理下标和第k元素位置对应
if (k <= pos) return Selectk(ar, left, index, k);
else
{
return Selectk(ar, index + 1, right, k - pos);//当在右边部分查找时,注意原第k元素要变成k-pos
}
}
int Select_k_Min(int* ar, int n, int k)
{
if (ar == NULL || n < 1 || k<0 || k>n) return -1;
return Selectk(ar, 0, n-1, k);
}
int main()
{
int num,i,k;
scanf("%d %d", &num,&k);
int a[num];
for(i=0;i<num;i++)
scanf("%d",&a[i]);
printf("第%d小的元素是%d",k,Select_k_Min(a,num,k));
return 0;
}
/********** End **********/
分治策略----寻找数组中第k小的元素
最新推荐文章于 2022-07-05 17:01:04 发布