在一个给定数组中找出最大的两个数:
算法:
预设两个最大数int 来存储数组中两个最大的数,保证max1在遍历数组过程中相比max2,一直是最大的。在遍历过程中数组中的其他数只与max2比较,小于max2时,取代max2,再与max1比较,后来再确保max1始终比max2大。时间复杂度O(n),线性!
/*
Try to find the 2 maximum number in an array
*/
#include <iostream>
#include <algorithm>
using namespace std;
void compare(int & , int & );
int main (){
int a[8]={2,123,31,21,42,1,421,0};
int max1,max2;
max1=a[0];
max2=a[1];
//Make sure that max1 always be the most largest number
compare(max1,max2);
//Traverse the array to assign number to max1 and max2;
for (int i=2; i<8; ++i) {
if (a[i]>max2) {
max2=a[i];
compare(max1, max2);
}
}
cout<<max1<<endl;
cout<<max2<<endl;
}
void compare(int & max1, int & max2){
if (max2>max1) {
swap(max1, max2);
}
}