How to get the second highest number in an array in Visual C#?

后端 未结 9 1803
误落风尘
误落风尘 2020-12-17 05:40

I have an array of ints. I want to get the second highest number in that array. Is there an easy way to do this?

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-17 05:50

    Getting the max number first, once the max is changed do a comparison against the second high number to see if it needs to swapped. The second if statement checks if the value is less than the max and is greater than the second highest value. Because of the short circuit, if the first condition fails then it exits the if and skips

        static void Main(string[] args)
        {
            //int[] arr = new int[10] { 9, 4, 6, 2, 11, 100, 53, 23, 72, 81 };
            int[] arr = { 1, 8, 4, 5, 12, 2, 5, 6, 7, 1, 90, 100, 56, 8, 34 };
            int MaxNum = 0;
            int SecNum = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] > MaxNum)
                {
                    if (MaxNum > SecNum) { SecNum = MaxNum; }
                    MaxNum = arr[i];
                }
    
                if (arr[i] < MaxNum && arr[i] > SecNum)
                {
                    SecNum = arr[i];
                }
            }
    
            Console.WriteLine("Highest Num: {0}. Second Highest Num {1}.", MaxNum, SecNum);
            Console.ReadLine();
        }
    

提交回复
热议问题