Created
June 22, 2017 13:53
-
-
Save akaliacius/ce599f8563ce386523bdd2e5b8586bb5 to your computer and use it in GitHub Desktop.
Method to find second largest value in array of integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int second(int[] array){ | |
if(array.length < 2) throw new IllegalStateException("minimum length of array must be 2"); | |
int max = Integer.MIN_VALUE; | |
int second = 0; | |
int counter = 0; | |
for(int i = 0; i < array.length; i++){ | |
if(array[i] > max) { | |
second = max; | |
counter++; | |
max = array[i]; | |
} | |
else if(array[i] > second && array[i] < max) { | |
second = array[i]; | |
counter++; | |
} | |
} | |
if(counter < 2) throw new IllegalStateException("all array values cannot be the same"); | |
return second; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment