好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

找出一个整数数组中,第二大的数(整数数组作为函数参数)

找出一个整数数组中,第二大的数(整数数组作为函数参数)

找出一个整数数组中,第二大的数(整数数组作为函数参数)
 static   void  Main( string  [] args)
 {
       int [] nums = {  1 ,  2 ,  10 ,  1 ,  5 ,  5 ,  3 ,  101 ,  11 ,  12 , - 1 ,  12   };
       int  secmax =  SecNum(nums, nums.Length);
      #region  数组不做参数时,直接在主函数中写
       //  int max = nums[0]; 
      ///  /int secmax = -1; 
      //  for (int i = 0; i < nums.Length; i++)
       //  {
       //      //  如果nums[i]大于最大数,那么就更新第二大数和最大数
        //      if (nums[i] > max)
       //      {
       //          secmax = max;
       //          max = nums[i];
       //      }
       //      else if (nums[i]>secmax)  //  当第二大的数字在最大的数后边时,上边的方法就不行了,必须加这个
      //                              //  如果nums[i]大于第二大的数 且小于最大数时 只更新第二大数就可以了
        //      {
       //          secmax = nums[i];
       //      }
       //  }
       //  Console.WriteLine("最大的数是:{0}",nums.Length);  
      #endregion  
     Console.WriteLine(  "  第二大的数是:{0}  "  ,secmax);
     Console.ReadKey();
 }

  private   static   int  SecNum( int [] nums,  int   length)
 {
       int  max = nums[ 0  ];
       int  secmax = - 1  ;
       for  ( int  i =  0 ; i < length; i++ )
     {
           //  如果nums[i]大于最大数,那么就更新第二大数和最大数 
          if  (nums[i] >  max)
         {
             secmax  =  max;
             max  =  nums[i];
         }
           else   if  (nums[i] > secmax) //  当第二大的数字在最大的数后边时,上边的方法就不行了,必须加这个
                                           //  如果nums[i]大于第二大的数 且小于最大数时 只更新第二大数就可以了 
         {
            secmax  =  nums[i];
        }
    }
      return   secmax;
} 

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于找出一个整数数组中,第二大的数(整数数组作为函数参数)的详细内容...

  阅读:40次