22
33import java .util .Arrays ;
44
5- //This code will find the Second Minimum in the given array
65/*
7- * say Given Array is {10,32,34,54,19,29,38,45}
6+ * Find the Second Minimum in the Given Array
7+ *
8+ * array {10,32,34,54,19,29,38,45}
89* minimum is 10, second minimum is 19
910*
10- * say Given Array is {10,20,30,40,50,60,70,80}
11+ * array is {10,20,30,40,50,60,70,80}
1112* minimum is 10, second minimum is 20
13+ *
14+ * The solution is, declare two variables
15+ * one variable to store minimum in the array
16+ * another variable to store second minimum
17+ *
1218*/
1319public class SecondMinimum {
1420 public static void main (String [] args ) {
1521
1622 int array [] = {10 ,32 ,34 ,54 ,19 ,29 ,38 ,45 };
17-
23+
24+ // assume 0th index value is minimum
1825 int min = array [0 ];
26+ // assume 1st index value is 2nd minimum
1927 int secondMin = array [1 ];
2028
29+ //if 1st index value is minimum than 0th index value
30+ //then swap the min and secondMin variable
2131 if (min > secondMin ){
2232 min = array [1 ];
2333 secondMin = array [0 ];
2434 }
2535
36+ //iterate from 2nd index
2637 for (int i =2 ;i <array .length ;i ++){
2738 if (array [i ] < min ){
39+ //if ith index is less than minimum
40+ //then update min and secondMin
2841 secondMin = min ;
2942 min = array [i ];
3043 }else if (array [i ] < secondMin ){
44+ //if ith index is not less than min
45+ //still need to check with secondmin
46+ //if ith index less than second min
47+ //then update only second min
3148 secondMin = array [i ];
3249 }
3350 }
@@ -39,10 +56,11 @@ public static void main(String[] args) {
3956}
4057/*
4158
42- OUTPUT
59+ OUTPUT
4360
44- Given array is : [10, 32, 34, 54, 19, 29, 38, 45]
45- Minimum value in the array is : 10
46- Second minimum value in the array is : 19
61+ Given array is :
62+ [10, 32, 34, 54, 19, 29, 38, 45]
63+ Minimum value in the array is : 10
64+ Second minimum value in the array is : 19
4765
4866*/
0 commit comments