c语言经典算法——查找一个整数数组中第二大数
来源:互联网 发布:淘宝飞鱼运动是正品么 编辑:程序博客网 时间:2024/06/02 13:13
https://www.cnblogs.com/dootoo/p/4473958.html
题目: 实现一个函数,查找一个整数数组中第二大数。
算法思想:
设置两个变量max1和max2,用来保存最大数和第二大数,然后将数组剩余的数依次与这两个数比较,如果这个数a比max1大,则先将max1赋给max2,使原先最大的数成为第二大的数,再将这个数a赋给max1,如果这个数a比max1小但比max2大,则将这个数a赋值给max2,依次类推,直到数组中的数都比较完。
c语言代码:
1 #include<stdio.h> 2 #include<stdlib.h> 3 #define N 10 4 void produce_random_array(int array[], int n); 5 void show_array(int array[], int n); 6 int search_second_max(int array[], int n); 7 int main(int agrc, char *agrv[]) 8 { 9 int array[N];10 produce_random_array(array, N);11 printf("原数组如下:\n");12 show_array(array, N);13 printf("\nthe second_max is: %d\n", search_second_max(array, N));14 system("pause");15 return 0;16 }17 void produce_random_array(int array[], int n)18 {19 int i;20 srand(time(NULL));21 for (i = 0; i < n; i++)22 {23 array[i] = rand() % 100;24 }25 }26 void show_array(int array[], int n)27 {28 int i;29 for (i = 0; i < n; i++)30 printf("%-3d", array[i]);31 }32 int search_second_max(int array[], int n)33 {34 int max1, max2, i;35 max1 = array[0];36 for (i = 1; i < n; i++)37 {38 if (array[i]>max1)39 {40 max2 = max1;41 max1 = array[i]; 42 }43 else44 {45 if (i == 1)46 max2 = array[i];47 else if (array[i]>max2)48 max2 = array[i];49 }50 }51 return max2;52 }
阅读全文
0 0
- c语言经典算法——查找一个整数数组中第二大数
- c语言经典算法——查找一个整数数组中第二大数
- 【我解C语言面试题系列】012 查找整数数组中第二大的数
- C语言面试题 4 (查找整数数组中第二大的数)
- 函数查找一个整数数组中第二大的数
- 找出整数数组中第二大数
- 写一个函数,找出一个整数数组中的第二大数
- C语言实现:查找一个整数中1的个数
- C语言编程练习——从一个字符数组中读出相应的整数、实数
- 查找数组中第二大的数(c语言)
- 求一个数组中第二大数...
- 一个数组中第一大数和第二大数
- 查找数组中的第二大数
- 查找第二大数的算法
- 数据结构——算法之(034)(编写一个函数求一个数组中的第二大数)
- 写一个算法实现在一个整数数组中,找出第二大的那个数字。
- 数据结构与算法——在一个数组中实现两个堆栈(C语言)
- C语言经典算法100例-029-求一个整数的位数且逆序打印
- 1063. 计算谱半径(20) PAT乙级真题
- linux下mount命令实现文件跨服务器的挂载
- 20171207-学习日记
- 60. 搜索插入位置
- 列举一些MongoEngine的filter方法
- c语言经典算法——查找一个整数数组中第二大数
- android开发如何获取电话号码的归属地信息
- 关于阿里矢量图iconfont的应用
- 总结 2017-12-07
- canvas调用webgl绘制图形图像
- C++标准库学习笔记-5-(Container)
- C到CPP的注释转换
- CentOS Redis 多实例
- 设计模式之中介者模式(Mediator)