寻找数组中的第二大数

寻找数组中第K大数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] ar = { 1, 25, 3, 4, 9, 6 ,9,7,10};
            try
            {
                Console.WriteLine(get2rdMax(ar).ToString());
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
            Console.ReadKey();
        }
        private static int get2rdMax(int[] ar)
        {
            int max = ar[0], s_max = ar[0];
            for (int i = 0; i < ar.Length; i++)
            {
               if (ar[i] > s_max)   //后面的跟第二大先比,if大,赋值给第二大,
                {
                    s_max = ar[i];    
                                      //第二大再跟最大比,if还大,第二大跟最大交换
                    if (s_max > max) //交换。一次最终:max>s_max>ar[i]
                    {                        
                        int temp;
                        temp = max;
                        max = s_max ;
                        s_max  = temp ;
                    }
                }
            }
            if (max == s_max)  //至少有两个一样的最大值
                throw new Exception("no second max!");
            else
                return s_max;
        }
    }
}
View Code

相关文章: