查找数组中的第二大数
2011-10-31 12:53
381 查看
1 /**********************************************************
2 *DESCRIPTION *
3 * Find the second big number from an array. *
4 *PARAMETERS *
5 * array is the array you want to look up; size is t-*
6 * he array's length; psec is used to store the seco-*
7 * nd big number. *
8 *RETURN VALUE *
9 * Parameters invalid, -1 is returned; Not find the *
10 * second big number, -2 is returned; Success, 0 is *
11 * returned. *
12 **********************************************************/
13 int find_second_big_number(const int array[], int size, int *psec)
14 {
15 int max;
16 int second;
17 int i = 0;
18
19 if (NULL == array || NULL == psec || size < 2)
20 {
21 return -1;
22 }
23
24 /* Initialize max and second */
25 for (i = 1; i < size; i++)
26 {
27 if (array[0] != array[i])
28 {
29 if (array[0] > array[i])
30 {
31 max = array[0];
32 second = array[i];
33 }
34 else
35 {
36 max = array[i];
37 second = array[0];
38 }
39 break;
40 }
41 }
42
43 if (i == size)
44 {
45 return -2;
46 }
47
48 /* Find the second big number */
49 for (; i < size; i++)
50 {
51 if (max < array[i])
52 {
53 second = max;
54 max = array[i];
55 }
56 else if(max > array[i] && second < array[i])
57 {
58 second = array[i];
59 }
60 }
61
62 *psec = second;
63
64 return 0;
65 }
2 *DESCRIPTION *
3 * Find the second big number from an array. *
4 *PARAMETERS *
5 * array is the array you want to look up; size is t-*
6 * he array's length; psec is used to store the seco-*
7 * nd big number. *
8 *RETURN VALUE *
9 * Parameters invalid, -1 is returned; Not find the *
10 * second big number, -2 is returned; Success, 0 is *
11 * returned. *
12 **********************************************************/
13 int find_second_big_number(const int array[], int size, int *psec)
14 {
15 int max;
16 int second;
17 int i = 0;
18
19 if (NULL == array || NULL == psec || size < 2)
20 {
21 return -1;
22 }
23
24 /* Initialize max and second */
25 for (i = 1; i < size; i++)
26 {
27 if (array[0] != array[i])
28 {
29 if (array[0] > array[i])
30 {
31 max = array[0];
32 second = array[i];
33 }
34 else
35 {
36 max = array[i];
37 second = array[0];
38 }
39 break;
40 }
41 }
42
43 if (i == size)
44 {
45 return -2;
46 }
47
48 /* Find the second big number */
49 for (; i < size; i++)
50 {
51 if (max < array[i])
52 {
53 second = max;
54 max = array[i];
55 }
56 else if(max > array[i] && second < array[i])
57 {
58 second = array[i];
59 }
60 }
61
62 *psec = second;
63
64 return 0;
65 }
相关文章推荐
- c语言经典算法——查找一个整数数组中第二大数
- 找出一个整数数组中的第二大数
- 找数组第二大数
- 找出整数数组中第二大数
- 查找一个数组中第二大的数的下标并输出
- 寻找数组中的第二大数
- 寻找数组中的第二大数
- [基础题]1.快速找出一个数组中的最大数、第二大数。
- 求数组中第二大数,不用排序额
- 寻找数组中的第二大数
- 函数查找一个整数数组中第二大的数
- C语言实现数组中查找最大值、最小值和第二大值
- C语言学习5-1:字符加法,字符串操作函数编写,查找数组中第二大的数
- O(n)时间内查找到无序数组当中的第二大元素
- 寻找数组中的第二大数
- 使用java从一个整数数组中查找第二大的数,仅用一次循环,不使用java自带的排序
- 快速找出数组中的最大数和第二大数
- 找数组中的第二大数
- 查找第二大数的算法