找出数组中的第二大值。C++实现
源码:
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
static const int MaxArray = 20;
int SecondValue(int a[], int n, int &Second)
{
if(n < 2){
return -1;
}
int first = a[0];
int second = a[1];
int i;
for(i = 0; i < n; i++){
if(first < a[i]){
second = first;
first = a[i];
}else if(first > a[i]){
if(second < a[i] || second == first){ //排除数组第0,1个值为最大值且相同的情况下,second的值永不会改变
second = a[i];
}
}
}
Second = second;
return 0;
}
//测试部分
int main(){
int i = 0;
int *arr = new int[MaxArray];
int Second;
int err;
srand((unsigned int)time(NULL));
arr[0] = arr[1] = 20;
for(i = 2; i < MaxArray; i++){
arr[i] = rand()%MaxArray;
cout << arr[i] << "\t";
}
cout << endl;
err = SecondValue(arr, MaxArray, Second);
delete []arr;
if(err < 0){
cout << "error" << endl;
exit(1);
}
cout << "second:" << Second << endl;
exit(0);
}
网上有很多找出第二大值的程序,但是很多都忽略了一个问题,如果数组的第0个和第1个值相等,且都为数组中的最大值,那么遍历的时候有可能会导致second的值永远不会发生改变。