求数组的最大值、第二大值

注意:数组的最大值同时存在多个的情况!

(1) 对比FindMax2和FindMax22两个函数的处理,细微差别导致结果不同!

(2) 当数组作为函数形参时,如果是常量数组,则最好添加const

(3) sizeof(arr)/sizeof(int)

(4) 随机数生成:

srand((unsigned)time(NULL));
rand() % randomNum; //生成randomNum以内的随机数

#include "stdafx.h"
#include <process.h>
#include <iostream>
#include "time.h"

using namespace std;

// find the maximum in an array.
int FindMax(const int* pArr, int nLen)  //最好加上const
{

    if (pArr != NULL)
    {
        int nMax = pArr[0];
        for (int i=1; i<nLen; i++)
        {
            if (nMax < pArr[i])
            {
                nMax = pArr[i];
            }
        }
        return nMax;
    }
    else 
        return 0;
}

// 找出最大和次大的数
void FindMax2(const int* pArr, int nLen, int* pMax1, int* pMax2)  //最好加上const
{
    *pMax1 = pArr[0];
    *pMax2 = 0;
    for (int i=1; i<nLen; i++)
    {
        if (*pMax1 < pArr[i])
        {
            *pMax2 = *pMax1;
            *pMax1 = pArr[i];
        }
        else if (*pMax1 > pArr[i])   //与下差别
        {
            if (*pMax2 < pArr[i])
            {
                *pMax2 = pArr[i];
            }
        }

    }
}

void FindMax22(const int* pArr, int nLen, int* pMax1, int* pMax2)  //最好加上const
{
    *pMax1 = pArr[0];
    *pMax2 = 0;
    for (int i=1; i<nLen; i++)
    {
        if (*pMax1 < pArr[i])
        {
            *pMax2 = *pMax1;
            *pMax1 = pArr[i];
        }
        else if (*pMax2 < pArr[i])   //与上差别
        {
            *pMax2 = pArr[i];
        }

    }
}



int _tmain(int argc, _TCHAR* argv[])
{
    int randomNum = 60;
    srand((unsigned)time(NULL));
    int arr[10];
    for(int i=0; i<10; i++)
    {
        arr[i] = rand() % randomNum;
        cout << arr[i] << '\t';
    }
    cout << endl;
    int result = FindMax(arr, 10);   // nLen = sizeof(arr)/sizeof(int)
    cout << "the max num in array is :" << result << endl;

    int max1 = 0;
    int max2 = 0;
    FindMax2(arr, sizeof(arr)/sizeof(int), &max1, &max2);
    cout << "the max two is :" << max1 << '\t' << max2 << endl;


    //数组的最大值存在多个
    int arr2[10] = {3,4,3,1,5,6,9,0,6,9};
    for(int i=0; i<10; i++)
    {
        arr[i] = rand() % randomNum;
        cout << arr2[i] << '\t';
    }
    FindMax2(arr2, sizeof(arr)/sizeof(int), &max1, &max2);
    cout << "the max two is :" << max1 << '\t' << max2 << endl;

    //函数对于存在大于一个的最大数情况,该函数不满足
    FindMax22(arr2, sizeof(arr)/sizeof(int), &max1, &max2);
    cout << "the max two is :" << max1 << '\t' << max2 << endl;


    system("pause");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值