forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSmallestAndSecondSmallest.java
32 lines (26 loc) · 1012 Bytes
/
SmallestAndSecondSmallest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.rampatra.arrays;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 7/30/15
*/
public class SmallestAndSecondSmallest {
private static int[] getSmallestAndSecondSmallest(int[] a) {
int smallest = Integer.MAX_VALUE, secondSmallest = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] < smallest) {
secondSmallest = smallest;
smallest = a[i];
} else if (a[i] < secondSmallest && a[i] != smallest) { // a[i] != smallest; if numbers are repeated in array
secondSmallest = a[i];
}
}
return new int[]{smallest, secondSmallest};
}
public static void main(String[] args) {
System.out.println(Arrays.toString(getSmallestAndSecondSmallest(new int[]{100, 1, 60, -10, -80, 85, 70, -80})));
System.out.println(Arrays.toString(getSmallestAndSecondSmallest(new int[]{100, 1, 60, 10, 80, 85, 70, 0})));
}
}