92. Second Largest element in an Array - prabhatrocks07/Core-Java-Programming GitHub Wiki

public class SecondLargestInArray {

public static void main(String[] args) {
	//int[] arr = new int[]{5, 19, 32, 91, 98};
	int[] arr = new int[]{10, 10, 10, 10};
	findSecondLargest(arr);
}

private static void findSecondLargest(int[] arr) {
	/* There should be at least elements */
	if(arr.length < 2) {
		System.out.println("Invalid input");
		return;
	}
	
	int first, second;
	
	first = second = Integer.MIN_VALUE;
	
	for (int i = 0; i < arr.length; i++) {
		// If current element is greater than first, then update both
		if(arr[i] > first) {
			second = first;
			first = arr[i];
		} else if(arr[i] > second && arr[i] != first){ // If arr[i] is in between first and second, then update second 
			second = arr[i];
		}
	}
	
	if(second == Integer.MIN_VALUE) {
		System.out.println("There is no second largest element");
	} else{
		System.out.println("The Second largest element is " + second);
	}
}
}