【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】
题目:
编写一个函数求一个数组中的第二大数
题目分析:
1、要想找到第二大数,很自然想到,你必须找到第一大数
2、顺序遍历数组,用两个零时变量记录当前的最大值和第二大值
算法实现:
#include <stdio.h>
int search_second_max(int *array, int size)
{
int max = 0, second_max = 0;
if(array[1] > array[0])
{
max = array[1];
second_max = array[0];
}
else
{
max = array[0];
second_max = array[1];
}
int i = 2;
for(; i<size; ++i)
{
if(array[i] > max)
{
second_max = max;
max = array[i];
}
else if(array[i] > second_max && array[i] < max)
{
second_max = array[i];
}
}
return second_max;
}
int main()
{
int a[] = {1, 65, 8, 4, 5, 65, 67, 9, 12, 35, 14, 67};
printf("------>%d\n", search_second_max(a, sizeof(a)/sizeof(int)));
return 0;
}

本文介绍了一种通过顺序遍历数组并使用两个临时变量来找出数组中第二大的数的算法。该方法首先比较数组的第一个元素和第二个元素,然后从第三个元素开始遍历,更新最大值和次大值。
755

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



