首页 文章详情

c语言经典算法——查找一个整数数组中第二大数

C语言题库 | 341 2021-07-22 12:30 0 0 0
UniSMS (合一短信)

题目:

实现一个函数,查找一个整数数组中第二大数。

算法思想:

设置两个变量max1和max2,用来保存最大数和第二大数,然后将数组剩余的数依次与这两个数比较,如果这个数a比max1大,则先将max1赋给max2,使原先最大的数成为第二大的数,再将这个数a赋给max1,如果这个数a比max1小但比max2大,则将这个数a赋值给max2,依次类推,直到数组中的数都比较完。

c语言代码:

//
// @author: 冲哥
// @date: 2021/7/11 11:46
// @description: 实现一个函数,查找一个整数数组中第二大数。

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

#define N 10

void produce_random_array(int array[], int n);
void show_array(int array[], int n);
int search_second_max(int array[], int n);

//搜索公众号C语言中文社区,后台回复“C语言”,免费获取200G编程资料。
int main(int agrc, char *agrv[]) {
    int array[N];
    produce_random_array(array, N);
    printf("原数组如下:\n");
    show_array(array, N);
    printf("\nthe second_max is: %d\n", search_second_max(array, N));
    system("pause");
    return 0;
}

void produce_random_array(int array[], int n) {
    int i;
    srand(time(NULL));
    for (i = 0; i < n; i++) {
        array[i] = rand() % 100;
    }
}

void show_array(int array[], int n) {
    int i;
    for (i = 0; i < n; i++)
        printf("%-3d"array[i]);
}

int search_second_max(int array[], int n) {
    int max1, max2, i;
    max1 = array[0];
    for (i = 1; i < n; i++) {
        if (array[i] > max1) {
            max2 = max1;
            max1 = array[i];
        } else {
            if (i == 1)
                max2 = array[i];
            else if (array[i] > max2)
                max2 = array[i];
        }
    }
    return max2;
}

运行结果

版权申明:内容来源网络,版权归原创者所有。除非无法确认,都会标明作者及出处,如有侵权,烦请告知,我们会立即删除并致歉!


good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter