本文共 1132 字,大约阅读时间需要 3 分钟。
写一段程序,找出数组中第k大小的数,输出数所在的位置。例如{2,4,3,4,7}中,
//写一段程序,找出数组中第k大小的数,输出数所在的位置。例如{2,4,3,4,7}中,//第一大的数是7,位置在4。第二大、第三大的数都是4,位置在1、3随便输出哪一个均可。 //函数接口为:int find_orderk(const int* narry,const int n,const int k)#include <cstdlib>#include <iostream>using namespace std;const int MAX = 5;int find_orderk(const int *vec, int n, int k){ int count = 1; int i = 0; for(; i<n; i++) { for(int j=0; j<n; j++) { if(vec[i] < vec[j]) count++; } if(count == k) return i; count = 1; } return 0; }int main(int argc, char *argv[]){ int vec[MAX] = {2,4,3,4,7}; cout << "init data: " << endl; for(int i=0; i<MAX; i++) { int temp = rand() % 100; vec[i] = temp; cout << temp << " " ; } cout << endl; int nth; while(cin >> nth) { assert(nth > 0 && nth <= MAX); cout << "pos is: " << find_orderk(vec, MAX, nth) << endl; } system("PAUSE"); return EXIT_SUCCESS;}
转载地址:http://gdkqb.baihongyu.com/