Saturday, August 24, 2019

Write an algorithm to find out the second largest element in an array.

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.
  1. public class SecondMaxElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4. int firstMax = Integer.MIN_VALUE, // large -ve value
  5.   int secondMax = Integer.MIN_VALUE; // large -ve value
  6. for (int i = 0; i < a.length; i++) {
  7. if (a[i] > firstMax) {
  8. secondMax = firstMax;
  9. firstMax = a[i]; // a[0] becomes first max
  10. } else if (a[i] > secondMax) {
  11. secondMax = a[i];
  12. }
  13. }
  14. System.out.println(secondMax);
  15. }
  16. }
Output:
10

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...