Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Design And SQL For DB2

Authors: James Cooper

1st Edition

1583473572, 978-1583473573

More Books

Students also viewed these Databases questions

Question

Discuss various types of training methods.

Answered: 1 week ago

Question

=+ What is the nature of the contracts or agreements with unions?

Answered: 1 week ago

Question

=+What is the procedure for labor relations in the workplace?

Answered: 1 week ago

Question

=+ Are ballots compulsory?

Answered: 1 week ago