Question
I am trying to get the second smallest using two different functions. But for some reason the second function prints out 2. But when I
I am trying to get the second smallest using two different functions. But for some reason the second function prints out 2. But when I comment the first function call out it will print out 3. Can anyone help explain why this is happening?
public static void main (String args[]) {
int [] input = {3,2,5,6};
System.out.println(minNum1(input));
System.out.println(minNum2(input));
}
public static int minNum1(int [] arr) {
int temp = 0;
int secondMin = 0;
for(int i = 0; i < arr.length; i++) {
for(int j = i + 1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
secondMin = arr[1];
}
}
return secondMin;
}
public static int minNum2(int [] arr) {
int min = arr[0];
int min2 = arr[1];
for(int i = 0; i < arr.length; i++) {
if(arr[i] < min) {
min2 = min;
min = arr[i];
}
else if(arr[i] < min2) {
min2 = arr[i];
}
}
return min2;
}
please run the code
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started