第6章 函数 第11题
程序员文章站
2022-07-12 22:48:25
...
题目:
设计一函数,在一个M个元素的整型数组中找出第N大的元素(N < M)。
代码:
#include <iostream>
using namespace std;
double function(double *a, int M, int N);
int main()
{
cout << "在一个M个元素的整型数组中找出第N大的元素(N < M)" << endl << endl;
int M, N;
cout << "请输入M的值:";
cin >> M;
double *a = new double[M];
cout << "请依次输入这M个元素:(彼此之间用空格隔开,按回车键结束)" << endl;
for (int i = 0; i < M; ++i) cin >> a[i];
cout << "请输入N的值:";
cin >> N;
cout << endl << "这" << M << "个元素的数组中,第" << N << "大的元素为:" << function(a, M, N) << endl << endl;
system("pause");
return 0;
}
double function(double *a, int M, int N)
{
bool judge;
double tmp;
//冒泡排序(从小到大)
for (int j = 1; j <= M - 1; ++j)
{
judge = false; //重置judge
for (int i = 0; i < M - j; ++i)
{
if (a[i] > a[i + 1])
{
tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
judge = true;
}
}
if (judge == false) break; //若本轮中没有发生交换,则提前退出
}
return a[M-N];
}