/******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
public class Main
{
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40};
System.out.println(secondLargest(arr, arr.length));
}
public static int secondLargest(int[] arr, int size) {
if (size < 2) {
throw new IllegalArgumentException("Array must have at least two elements");
}
int largestIndex = 0;
for (int i = 1; i < size; i++) {
if (arr[i] > arr[largestIndex]) {
largestIndex = i; // Find the index of the largest value
}
}
int temp = arr[0];
arr[0] = arr[largestIndex];
arr[largestIndex] = temp; // Swap the largest with the first
int secondLargest = arr[1];
for (int i = 2; i < size; i++) {
if (arr[i] > secondLargest) {
secondLargest = arr[i]; // Find the second largest in the rest
}
}
return secondLargest;
}
}