Sunday, April 14, 2024
HomeSoftware EngineeringReturn Nth Smallest Component in Java

# Return Nth Smallest Component in Java

## The problem#

Given an array/checklist [] of integers, Discover the Nth smallest ingredient on this array of integers

Notes

• Array/checklist dimension is no less than 3 .
• Array/checklist’s numbers may very well be a combination of positives , negatives and zeros .
• Repetition in array/checklist’s numbers may happen, so don’t Take away Duplications .

Examples

``````nthSmallest({3,1,2} ,2) ==> return (2)
nthSmallest({15,20,7,10,4,3} ,3) ==> return (7)
nthSmallest({2,169,13,-5,0,-1} ,4) ==> return (2)
``````

## The answer in Java code#

Choice 1:

``````public class Answer {
public static int nthSmallest(closing int[] arr, closing int n) {
java.util.Arrays.type(arr);
for(int i=0; i<arr.size; i++) {
if (i==n-1) return arr[i];
}
return 0;
}
}
``````

Choice 2:

``````import java.util.Arrays;
public static int nthSmallest(closing int[] arr, closing int n) {
Arrays.type(arr);
return arr[n - 1];
}
}
``````

Choice 3:

``````import java.util.Arrays;

public static int nthSmallest(closing int[] arr, closing int n) {
return Arrays.stream(arr).sorted().skip(n-1).findFirst().getAsInt();
}
}
``````

## Take a look at circumstances to validate our answer#

``````import org.junit.Take a look at;
import static org.junit.Assert.assertEquals;
import org.junit.runners.JUnit4;

public class SampleTest {
@Take a look at
public void checkPositiveValues() {
doTest(new int[]{3, 1, 2}, 2, 2);
doTest(new int[]{15, 20, 7, 10, 4, 3}, 3, 7);
}
@Take a look at
public void checkNegativeValues() {
doTest(new int[]{-5, -1, -6, -18}, 4, -1);
doTest(new int[]{-102, -16, -1, -2, -367, -9}, 5, -2);
}
@Take a look at
public void checkMixedValues() {
doTest(new int[]{2, 169, 13, -5, 0, -1}, 4, 2);
doTest(new int[]{177, 225, 243, -169, -12, -5, 2, 92}, 5, 92);
}
non-public void doTest(closing int[] arr, closing int n, closing int anticipated) {
}
}
``````
RELATED ARTICLES