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

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;
}
原文地址:https://www.cnblogs.com/wdmhn/p/3031655.html