数据结构——算法之(034)(编写一个函数求一个数组中的第二大数)

来源:互联网 发布:python绘制散点图矩阵 编辑:程序博客网 时间:2024/05/10 07:19

【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱: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;}


0 0