栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > C++面试题库

写一段程序,找出数组中第k大小的数,输出数所在的位置。

写一段程序,找出数组中第k大小的数,输出数所在的位置。

例如{2,4,3,4,7}中,第一大的数是7,位置在4。第二大、第三大的数都是4,位置在1、3随便输出哪一个均可。函数接口为:int find_orderk(const int* narry,const int n,const int k)
要求算法复杂度不能是O(n^2)
//快速排序
#include
usingnamespacestd;
intPartition (int*L,intlow,int high)
{
inttemp = L[low];
intpt = L[low];
while (low < high){while (low < high && L[high] >= pt)
–high;
L[low] = L[high];
while (low < high && L[low] <= pt)++low;L[low] = temp;}L[low] = temp;returnlow;}voidQSort (int*L,intlow,int high){if (low < high){intpl = Partition (L,low,high);QSort (L,low,pl - 1);QSort (L,pl + 1,high);}}intmain (){intnarry[100],addr[100];intsum = 1,t;cout << "Input number:" << endl;cin >> t;
while (t != -1)
{
narry[sum] = t;
addr[sum – 1] = t;
sum++;
cin >> t;
}
sum -= 1;
QSort (narry,1,sum);
for (int i = 1; i <= sum;i++)cout << narry[i] << 't';cout << endl;intk;cout << "Please input place you want:" << endl;cin >> k;
intaa = 1;
intkk = 0;
for (;;)
{
if (aa == k)
break;
if (narry[kk] != narry[kk + 1])
{
aa += 1;
kk++;
}
}
cout << "The NO." << k << "number is:" << narry[sum - kk] << endl;cout << "And it's place is:" ;for (i = 0;i < sum;i++){if (addr[i] == narry[sum - kk])cout << i << 't';}return0;}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/265777.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号