Learnitweb

Java Program to find second largest number in Array

Approach 1

Sort the array in descending order and then return the second element from the array. The time complexity of this solution is O(nlogn). This solution has problem if first two numbers in sorted array are equal.

Approach 2

Second and a better solution is to traverse the array twice. In first traversal find the largest number. In second traversal compare and find the largest number but which is less than the largest number found in first iteration.

Approach 3

Best solution is to find largest number in one traversal.

public class SecondLargestNumberExample {
	// Function to find second largest number
	public static void getSecondLargest(int array[], int arraySize) {
		int i, largest, secondLargest;
		// there should be at least two elements to find second largest
		if (arraySize < 2) {
			System.out.print(" Invalid Input ");
			return;
		}

		largest = Integer.MIN_VALUE;
		secondLargest = Integer.MIN_VALUE;
		for (i = 0; i < arraySize; i++) {
			/*
			 * If current element is smaller than largest then update both largest and
			 * secondLargest
			 */
			if (array[i] > largest) {
				secondLargest = largest;
				largest = array[i];
			}

			/*
			 * If current element is in between largest and secondLargest then update
			 * secondLargest
			 */
			else if (array[i] > secondLargest && array[i] != largest)
				secondLargest = array[i];
		}

		if (secondLargest == Integer.MIN_VALUE)
			System.out.print("There is no second largest element\n");
		else
			System.out.print("The second largest element is " + secondLargest);
	}

	
	public static void main(String[] args) {
		int array[] = { 1, 3, 5, 8, 2, 0, 9, 11 };
		int arrayLength = array.length;
		getSecondLargest(array, arrayLength);
	}
}

Output

The second largest element is 9