findSecondLargestNumberInTheArray() method returns the second highest number from an array.
Could you please review this code to enhance performance.
public static int findSecondLargestNumberInTheArray(int array[]) {
// 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 current element is greater than highest
if (array[i] > highest) {
// assign second highest element to highest element
secondHighest = highest;
// highest element to current element
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
return secondHighest;
}
Integer.MIN_VALUEand instead populate the initial values ofhighestandsecondHighestfrom the first two values in the array in the appropriate order. Then start your loop fromi = 2to process the rest of the array. A two element array will not enter the first loop iteration. \$\endgroup\$