Saturday, August 24, 2019

Write an algorithm to find out the second smallest 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 smallest element in the array.

  1. public class SecondMinElement {
  2. public static void main(String[] args) {
  3. int a[] = { 3, 4, 1, 105, 10, -10 };
  4. int firstMin = Integer.MAX_VALUE;
  5. int secondMin = Integer.MAX_VALUE;
  6. for (int i = 0; i < a.length; i++) {
  7. if (a[i] < firstMin) {
  8. secondMin = firstMin;
  9. firstMin = a[i];
  10. } else if (a[i] < secondMin) {
  11. secondMin = a[i];
  12. }
  13. }
  14. System.out.println("Second min element: " + secondMin);
  15. }
  16. }
Output:
Second min element: 1

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...