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

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...