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?
10 Answers
Try this (using LINQ):
int secondHighest = (from number in numbers
orderby number descending
select number).Skip(1).First();

- 38,647
- 50
- 150
- 207
-
You should be able to replace `.ToList()[0]` with `.First()`. – Fredrik Mörk Nov 28 '09 at 07:57
-
1Anyone able to comment on how efficient this is compared to a raw loop method like @Gene Goykhman's version? – mike Nov 28 '09 at 09:14
-
It's not as efficient, but unless you're sorting a MASSIVE list of ints, this is the best way to go. The best way to go is to performance benchmark then only speed up the bottlenecks. And you only need to do that if it's actually running slow. – RCIX Nov 28 '09 at 10:32
-
3Does LINQ not have a partial sort? Yes, optimisation should be concentrated at bottlenecks. But if you have a choice of algorithms, and the code for each is about as complicated, you aren't obliged to deliberately pick the slower one in order to avoid "premature optimisation" ;-) – Steve Jessop Nov 28 '09 at 11:33
-
Good point. I don't know of any way to partially sort lists with linq, but it would be a good question :) – RCIX Nov 29 '09 at 06:37
-
However there are some cases which will fail that are if list has same number more than once so doing `distinct` would solve that problem. – Mahesh Sep 01 '17 at 06:50
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);

- 1,981
- 2
- 16
- 15
-
3you may as well initialise largest and second to int.MinValue and make no assumptions ;) – Martin Nov 28 '09 at 12:56
-
-
The loop needs to keep track of both the largest and 2nd largest integer encountered so far. The `else if` handles the case of the candidate number not being the largest, but rather being the 2nd largest it has encountered. – Gene Goykhman Sep 25 '16 at 08:41
Yes, have 2 vars (first and second) passthrough the array and each time compair what you get with this two cells (always putting the highest on first and the 2nd highest on second) with one pass you will get the 2nd higher on the second var.

- 14,639
- 11
- 62
- 110
You don't specify if you want to do this with the minimum complexity.
Assuming your array is unsorted, please see: How to find the kth largest element in an unsorted array of length n in O(n)?
To find Kth largest element in an unsorted array: Build a max heap in O(n). Now remove k elements from the heap; where each removal costs log(n) time to maintain the heap. Total time complexity = O(n + klogn)
To understand building Max heap in O(n) see Binary heap

- 1
- 1

- 295,962
- 43
- 465
- 541
-
How can the total complexity be O(k log n) when there's an O(n) step? – Jon Skeet Nov 28 '09 at 07:50
-
Who cares about toal complexity or binary heaps when you can do what you want simply with LINQ? :D – RCIX Nov 28 '09 at 08:58
-
Thanks Jon. The initial step to build the heap is O(n); subsequent removes are each O(logn). – Mitch Wheat Nov 28 '09 at 09:54
-
@RCIX: yeah who cares about complexity...until you come up against a few thousans elements and you happen to be using an O(n^2) algorithm! – Mitch Wheat Nov 28 '09 at 09:55
-
-
1
max1=0;
max2=0;
for( int i=0; i < a.Length; i++)
{
if (arr[i]> max1)
{
max2=max1;
max1=arr[i];
}
else
{
if (a[i]!= max1) && ( a[i] > max2)
max2[i]=arr[i];
}
}

- 1,936
- 4
- 24
- 46

- 11
- 1
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();
}
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);

- 17
- 1
-
1This blocks of code results the highest as well as second highest number in an array. – Mukesh Kumar Apr 06 '12 at 09:50
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());

- 1,744
- 1
- 25
- 44

- 17
- 3
static void Main(string[] args)
{
int[] myArray = new int[] { 0, 1, 2, 3, 13, 8, 5,12,11,14 };
int num1 = 0, temp = 0;
for (int i = 0; i < myArray.Length; i++)
{
if (myArray[i] >= num1)
{
temp = 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);
Console.ReadKey();
}
There are two possibilities to find second highest number from an array.
1). Find second max number from an array.
int[] myArray = { 0, 2, 3, 8, 13};
int max = 0;
int second_max = 0;
foreach (int arr in myArray) {
if (arr > max)
{
second_max = max;
max = arr;
}
}
Console.WriteLine("First highest number is: "+max);
Console.WriteLine("Second highest number is: " + second_max);
2). Find second max number with the smallest complexity from an array.
int[] myArray = { 0, 2, 3, 13, 8};
//smaller number is given after
larger number
int max = 0;
int second_max = 0;
foreach (int arr in myArray) {
if (arr > max)
{
second_max = max;
max = arr;
}
else if (arr > second_max)
{
second_max = arr;
}
}
Console.WriteLine("First highest number is: "+max);
Console.WriteLine("Second highest number is: " + second_max);

- 2,733
- 26
- 47