输出数组中第二大数

class Program
    {
        private static int get2rdMax(int[] ar)
        {
            int max = ar[1], s_max = ar[1];
            for (int i = 0; i < ar.Length; i++)
            {
                if (ar[i] > s_max)
                {
                    s_max = ar[i];
                    if (s_max > max)
                    {
                        max += s_max;
                        s_max = max - s_max;
                        max -= s_max;
                    }
                }
            }

            if (max == s_max)
                throw new Exception("no second max!");
            else
                return s_max;
        }

        static void Main(string[] args)
        {
            int[] ar = { 1, 2, 3, 4, 5, 6 };
            try
            {
                Console.WriteLine(get2rdMax(ar).ToString());
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
            Console.ReadKey();

        }
    }
原文地址:https://www.cnblogs.com/jobs2/p/3018790.html