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

后端 未结 9 1781
误落风尘
误落风尘 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条回答
  •  萌比男神i
    2020-12-17 06:01

    You could sort the array and choose the item at the second index, but the following O(n) loop will be much faster.

    int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
    int largest = int.MinValue;
    int second = int.MinValue;
    foreach (int i in myArray)
    {
        if (i > largest)
        {
            second = largest;
            largest = i;
        }
        else if (i > second)
            second = i;
    }
    
    System.Console.WriteLine(second);
    

提交回复
热议问题