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

后端 未结 9 1784
误落风尘
误落风尘 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:51

    int[] arr = { 1, 8, 4, 5, 12, 2, 5, 6, 7, 1, 90, 100, 56, 8, 34 };
    
    int first, second;
    // Assuming the array has at least one element:
    first = second = arr[0];
    for(int i = 1; i < arr.Length; ++i)
    {
      if (first < arr[i])
      {
        // 'first' now contains the 2nd largest number encountered thus far:
        second = first;
        first = arr[i];
      }
    
    }
    MessageBox.Show(second.ToString());
    

提交回复
热议问题