简体   繁体   中英

Find the k smallest integer in an array

Here is my code, it works for finding 1-7 smallest integers, but 8 and 9. It returns null when I find 8 smallest integer in the array. Can anyone help me where is the problem? I am using quicksort here. Thanks very much!

update: I have figured out the problem, which is the array in the main function. After I change to the following look,

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 front, int end, int k){
    if(front>=end) return null;
    int pivot = partition(input,front,end);
    //System.out.println(pivot);
    if(k==pivot){
        return Arrays.copyOfRange(input,0,pivot);
    }
    else {
        if(k<pivot) 
            return findK(input,front,pivot,k); 
        return findK(input,pivot+1,end,k);
    }
}
public static int[] findKSamllest(int[] input, int k){
    return findK(input, 0, input.length-1, k);
}

}

Change

if(front >= end) return null;

to

if(front > end) return null;

Stand on the shoulders of giants and use the libraries that are already available:

Arrays.sort(myArray);
int[] returnArray = new int(NUM_ITEMS_TO_RETURN);
for (int i=0; i < NUM_ITEMS_TO_RETURN; i++)
{
   returnArray[i] = myArray[i];
}

return returnArray;

Obviously you have to do some error checking, for example that the initial array is larger or equal to the number of items you want returned, but that's trivial.

You could save you a bit time and impress your teacher with the fancy new Java 8 API.

It provides streams and useful functions to solve this in one (long) line or 5, if it should be readable ;-)

final List<Integer> sortedKList = Arrays.asList(7, 2, 4, 8, 3, 5, 1, 0, 10)
    .stream()
    .sorted()
    .limit(7)
    .collect(Collectors.toList());

You can then review your result with:

sortedKList.forEach(System.out::println);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM