Write a Java program to find the second largest element in an array.
This program finds the second largest element in an array.
class Main {
public static void main(String[] args) {
int[] arr = {3, 56, 8, 43, 44}; // Example array
// Call the method to find the second largest element
int secondLargest = findSecondLargest(arr);
// Print the second largest element if found
if (secondLargest != -1) {
System.out.println("Second largest element: " + secondLargest);
} else {
System.out.println("There are no second largest element.");
}
}
// Method to find and return the second largest element in the array
public static int findSecondLargest(int[] arr) {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
// Loop through the array to find the largest and second largest elements
for (int i = 0; i < arr.length; i++) {
if (arr[i] > largest) {
secondLargest = largest; // Update second largest
largest = arr[i]; // Update largest
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i]; // Update second largest
}
}
// If second largest is still Integer.MIN_VALUE, return -1 indicating no second largest element
if (secondLargest == Integer.MIN_VALUE) {
return -1; // No second largest element found
} else {
return secondLargest; // Return the second largest element
}
}
}
Output:
Second largest element: 44
How It Works
- Initialization:
- largest and secondLargest are initialized to Integer.MIN_VALUE to ensure they can store any value in the array.
- Finding the Largest and Second Largest:
- If the current element (arr[i]) is greater than largest:
- Update secondLargest to the value of largest.
- Update largest to the current element.
- Else if the current element is greater than secondLargest and not equal to largest, update secondLargest.
- If the current element (arr[i]) is greater than largest:
- Edge Case Handling:
- If secondLargest remains Integer.MIN_VALUE, the method returns -1, indicating there is no valid second largest element.
- Output:
- If a second largest element exists, it prints the value. Otherwise, it prints a message saying no second largest element exists.
Edge Cases
- Array with One Element:
- Input: arr = {5}
- Output: There are no second largest element.
- Array with Identical Elements:
- Input: arr = {3, 3, 3, 3}
- Output: There are no second largest element.
- Negative Numbers:
- Input: arr = {-3, -1, -7, -5}
- Output: Second largest element: -3
Advantages
- Efficient: Time complexity is O(n) with a single loop through the array.
- Space Efficient: No additional data structures are used, so space complexity is O(1).