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

后端 未结 9 1755
误落风尘
误落风尘 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 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);
    
    0 讨论(0)
  • 2020-12-17 06:04

    Try this (using LINQ):

    int secondHighest = (from number in numbers
                         orderby number descending
                         select number).Skip(1).First();
    
    0 讨论(0)
  • 2020-12-17 06:08
        int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5 };
        int num1=0, temp=0;
        for (int i = 0; i < myArray.Length; i++)
        {
            if (myArray[i] >= num1)
            {
                num1 = myArray[i];
            }
            else if ((myArray[i] < num1) && (myArray[i] > temp))
            {
                temp = myArray[i];
            }
        }
        Console.WriteLine("The Largest Number is: " + num1);
        Console.WriteLine("The Second Highest Number is: " + temp);
    
    0 讨论(0)
提交回复
热议问题