C# 求数组中第二大数值

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();

        }
    }

posted on 2012-10-15 17:20  YuanSong  阅读(2365)  评论(0编辑  收藏  举报

导航