Find Second largest element in an array | Code Factory


Donate : Link

Medium Blog : Link

Applications : Link

Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array.

Please first try to do it yourself, then move to the solution.

1) Initialize two variables "max" and "secondMax" to arr[0] as
     max = secondMax = arr[0]
2) Start traversing the array,
     a) If the current element in array say arr[i] is greater than "max". Then update "max" and "secondMax" as,
          secondMax = max;
          max = arr[i];
     b) If the current element is greater than "secondMax",
          secondMax = arr[i];

. . . . .

package com.example.java.programming;

/**
 * @author code.factory
 */
public class Test {
	public static void main(String... strings) throws Exception {
		int a[] = { 7, 2, 1, 5, 11, -7, 0, 3, 219 };
		find(a);
		
		a = new int[] {12, -8, 13, 20, 4, 6};
		find(a);
		
		a = new int[] {65, 80, 90, 302, 115, 250, 175};
		find(a);
	}
	
	private static void find(int a[]) {
		int max = a[0];
		int secondMax = a[0];
		for (int i = 1; i < a.length; i++) {
			if (max < a[i]) {
				secondMax = max;
				max = a[i];
			} else if (secondMax < a[i]) {
				secondMax = a[i];
			}
		}

		System.out.println("Max is " + max + " and 2nd Max is " + secondMax);
	}
}

Output:

Max is 219 and 2nd Max is 11
Max is 20 and 2nd Max is 13
Max is 302 and 2nd Max is 250

Leave a comment