查找数组中的第二大数

来源:互联网 发布:银河证券软件下载 编辑:程序博客网 时间:2024/05/21 09:04
  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 }

原创粉丝点击