Finding the second highest number in array
I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:
static int secondHighest(int... nums) {
int high1 = Integer.MIN_VALUE;
int high2 = Integer.MIN_VALUE;
for (int num : nums) {
if (num > high1) {
high2 = high1;
high1 = num;
} else if (num > high2) {
high2 = num;
}
}
return high2;
}
This is O(N)
in one pass. If you want to accept ties, then change to if (num >= high1)
, but as it is, it will return Integer.MIN_VALUE
if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE
if the array contains only the same number.
// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;
// Loop over the array
for (int i = 0; i < array.Length; i++) {
// If we've found a new highest number...
if (array[i] > highest) {
// ...shift the current highest number to second highest
secondHighest = highest;
// ...and set the new highest.
highest = array[i];
} else if (array[i] > secondHighest)
// Just replace the second highest
secondHighest = array[i];
}
}
// After exiting the loop, secondHighest now represents the second
// largest value in the array
Edit:
Whoops. Thanks for pointing out my mistake, guys. Fixed now.If the first element which second_highest is set to initially is already the highest element, then it should be reassigned to a new element when the next element is found. That is, it's being initialized to 98, and should be set to 56. But, 56 isn't higher than 98, so it won't be set unless you do the check.
If the highest number appears twice, this will result in the second highest value as opposed to the second element that you would find if you sorted the array.