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