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
-
- Start traversing the array,
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.