利用快速排序的方法尋找第k小的數據,該方法的時間複雜度平均爲O(n),可以滿足一般情況下的查找算法
#include <stdio.h>
// res代表開始查找的元素的地址,n代表查找的範圍,nTh代表查找該範圍內的第nTh小的元素
int FindNth(int*res,int n,int nTh)
{
//如果查找的範圍爲1,直接返回該元素
if (n<=1)
{
return *res;
}
int i=0,j=n-1;
int temp=*res;
while (i<j)
{
while (res[j]>=temp && i<j)
{
j--;
}
if (i<j)
{
res[i]=res[j];
}
while(res[i]<=temp && i<j)
{
i++;
}
if (i<j)
{
res[j]=res[i];
}
}
res[i]=temp;
//如果剛好找到該元素則直接返回
if (i==nTh-1)
{
return res[i];
}
//如果該元素在右邊(即是元素值較大的那邊,修改查找範圍,在該範圍內尋找第nTh-i-1小的元素)
if (i<nTh-1)
{
return FindNth(res+i+1,n-i-1,nTh-i-1);
}
//修改查找範圍,尋找第nTh小的元素
else
{
return FindNth(res,i,nTh);
}
}
int main()
{
int n,data[1000],nTh;
scanf("%d%d",&n,&nTh);
for (int i=0;i<n;i++)
{
scanf("%d",&data[i]);
}
printf("%d\n",FindNth(data,n,nTh));
}