在一个数组中找到最大的两个数

在一个给定数组中找出最大的两个数:

算法:

预设两个最大数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);
    } 
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值