How to return the smallest integers from array?
I have an array int[] a= {5,3,1,2} and I want to make a method that picks
out the "k" smallest numbers and return an array with the k smallest
integers in ascending order. But when I run this code I get the output:
[1,3]. I know the code skips some numbers somehow, but I cant twist my
brain to fix it. Any ideas?
public static int[] nrSmallest(int[] a, int k) {
if(k <1 || k>a.length)
throw new IllegalArgumentException("must be at least 1");
int[] values= Arrays.copyOf(a, k);
Arrays.sort(values);
int counter= k-1;
for(int i= k; i < a.length; i++) {
if(a[i]< values[counter]) {
for(int j= k-1; j> counter; j--) {
if(values[j]> values[j-1])
values[j]= values[j-1];
else if(values[j]< values[j-1]) {
int temp= values[j-1];
values[j-1]= values[j];
values[j]= temp;
}
}
if(a[i]< values[counter])
values[counter]= a[i];
}
if(counter> 0) counter--;
}
return values;
}
No comments:
Post a Comment