Problem statement:
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the second largest element in the array.
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the second largest element in the array.
- public class SecondMaxElement {
- public static void main(String[] args) {
- int a[] = { 3, 4, 1, 105, 10, -10 };
- int firstMax = Integer.MIN_VALUE, // large -ve value
- int secondMax = Integer.MIN_VALUE; // large -ve value
- for (int i = 0; i < a.length; i++) {
- if (a[i] > firstMax) {
- secondMax = firstMax;
- firstMax = a[i]; // a[0] becomes first max
- } else if (a[i] > secondMax) {
- secondMax = a[i];
- }
- }
- System.out.println(secondMax);
- }
- }
Output:
10
No comments:
Post a Comment