Java program to find second largest number in an array ?

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

Algorithm:

  • Initialize two variables first and second to INT_MIN as,
    • first = second = INT_MIN

a) If the current element in array say arr[i] is greater than first. Then update first and second as,

    • second = first
    • first = arr[i]
    b) If the current element is in between first and second, then update second to store the value of current variable as

    • second = arr[i]
  • Return the value stored in second.

step 1

  • Iterate the given array.

Step 2 (first if condition arr[i] > largest):

  • If current array value is greater than largest value then move the largest value to secondLargest and make current value as largest

Step 3 (second if condition arr[i] >secondLargest )

  • If the current value is smaller than largest and greater than secondLargest then the current value becomes secondLargest.

Sample code in Java

public class SecondLargest {

public static void main(String[] args) {

int arr[] = { 24, 56, 57, 105, 102, 62, 58, 46, 76, 95 };
int largest = arr[0];
int secondLargest = arr[0];

System.out.println("The given array is:" );
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+"\t");
}
for (int i = 0; i < arr.length; i++) {

if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];

} else if (arr[i] > secondLargest) {
secondLargest = arr[i];

}
}

System.out.println("\nSecond largest number is:" + secondLargest);

}
}

Output

The given array is:
24	56	57	105	 102  62  58  46  76  95	
Second largest number is:102

Categorized in:

Java

Tagged in:

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Share Article:

Leave a Reply

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock