题目: 实现一个函数,查找一个整数数组中第二大数。
算法思想:
设置两个变量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 else
44 {
45 if (i == 1)
46 max2 = array[i];
47 else if (array[i]>max2)
48 max2 = array[i];
49 }
50 }
51 return max2;
52 }