Skip to content

Instantly share code, notes, and snippets.

@akaliacius
Created June 22, 2017 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaliacius/ce599f8563ce386523bdd2e5b8586bb5 to your computer and use it in GitHub Desktop.
Save akaliacius/ce599f8563ce386523bdd2e5b8586bb5 to your computer and use it in GitHub Desktop.
Method to find second largest value in array of integers
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