Java – find K minimum integers in the array
•
Java
This is my code, which is suitable for finding 1-7 minimum integers, but 8 and 9 When I find the eight smallest integers in the array, it returns null Can anyone help me solve the problem? I use quicksort here
Update: I have found the problem. This is the array in the main function After I changed to the following,
int[] arr = {2,3,1,7,5,6,20,8,4,9};
and
if(front>=end) return input;
It works now!
import java.util.Arrays; import java.io.*; class quicksort{ public static void main(String[] args){ int[] arr = new int[9]; arr[0] = 7; arr[1] = 2; arr[2] = 4; arr[3] = 8; arr[4] = 3; arr[5] = 5; arr[6] = 1; arr[7] = 0; arr[8] = 10; System.out.println((Arrays.toString(findKSamllest(arr,8)))); } public static int partition(int[] input,int front,int end){ int pivot = input[front]; while(front < end){ while(input[front]<pivot) front++; while(input[end]>pivot) end--; swap(input,front,end); } return front; } public static void swap(int[] input,int s,int l){ int temp = input[s]; input[s] = input[l]; input[l] = temp; } public static int[] findK(int[] input,int end,int k){ if(front>=end) return null; int pivot = partition(input,end); //System.out.println(pivot); if(k==pivot){ return Arrays.copyOfRange(input,pivot); } else { if(k<pivot) return findK(input,pivot,k); return findK(input,pivot+1,end,k); } } public static int[] findKSamllest(int[] input,int k){ return findK(input,input.length-1,k); }
}
Solution
change
if(front >= end) return null;
to
if(front > end) return null;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码