How to find second smallest in arrays in java || Second smallest from array || Java || Fox Tech

preview_player
Показать описание
How to find smallest element in array :

How to find second smallest from array in java
How to find second smallest
Program for finding second smallest

TCS NQT Top 10 coding questions :

If you have any query comment below.
If you have another solution for this question you can share it with us
We will give you credit and make video on it. So that other students can also know the different approach.

If you like this solution,
Don't forget to like, share and subscribe.
Рекомендации по теме
Комментарии
Автор

another way is using arr[0] and arr[1] instead of Integer.Max_Value for both. Because this case we assume arr[0] is the smallest. if it is the smallest by chance then we are good. if not it will search for smallest and give it the index of 0. same goes for arr[1]. We assume arr[1] is the second smallest and if it isn't the system searches for the second smallest value and gives it the index of 1.

public static void main(String[] args) {
// 1. method “int GetSecondMin(int[] array)
int array[] = {7, 2, 9, 5, 4, 15, 6, 1};



}//End of Main

// 1. method “int GetSecondMin(int[] array)
static int GetSecondMin(int[] array){
int firstMin = array[0];
int secondMin = array[1];

for(int i = 0; i < array.length; i++){

if(array[i] > firstMin){
firstMin = array[i];

}
else if(array[i] > firstMin && array[i] < secondMin){
secondMin = array[i];
}

}
return secondMin;
}//End of GetSecondMin

PunjabiKush