第二大的数获取路径有两条:
1 从最大数传下来
2 直接赋值得到(当前数比最大值小,比当前的第二大数大)
代码如下:
/*************************************************************************
> File Name: second_max.c
> Author: hai--feng
> Mail: haifeng@126.com
> Created Time: Mon 25 Jun 2012 05:50:49 PM CST
************************************************************************/
#include<stdio.h>
const int men_count = 9;
int SearchSecondMaxValue(const int group[], int count)
{
int max = 0, smax = 0;
int times = count;
int *pdata = group;
smax = max = *pdata;
while(times != 0)
{
if(max < *pdata)
{
smax = max;
max = *pdata;
}
if(max > *pdata && smax < *pdata)
{
smax = *pdata;
}
pdata++;
times--;
}
return smax;
}
int main(void)
{
int group[] = {7,0,1,2,3,8,4,5,6};
int value = 0;
value = SearchSecondMaxValue(group, men_count);
printf("second value = %d\n",value);
return 0;
}
执行结果:
second value = 7
本文介绍了一种寻找数组中第二大的数值的算法实现。通过一次遍历,同时跟踪最大值和第二大的值,确保了高效性。适用于需要快速找到次优解的应用场景。
1万+

被折叠的 条评论
为什么被折叠?



