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.
Given an array of positive and negative unsorted integer. Can you write an algorithm to find out the second smallest element in the array.
- public class SecondMinElement {
- public static void main(String[] args) {
- int a[] = { 3, 4, 1, 105, 10, -10 };
- int firstMin = Integer.MAX_VALUE;
- int secondMin = Integer.MAX_VALUE;
- for (int i = 0; i < a.length; i++) {
- if (a[i] < firstMin) {
- secondMin = firstMin;
- firstMin = a[i];
- } else if (a[i] < secondMin) {
- secondMin = a[i];
- }
- }
- System.out.println("Second min element: " + secondMin);
- }
- }
Output:
Second min element: 1
No comments:
Post a Comment