jwkoo
jwkoo

Reputation: 2653

find the kth smallest number in java

Below is the java code to find the kth smallest number in array. This code is for elementary version, not using pivot-index.

class Func {
    int kthSmallest(int arr[], int smallestIndex, int size){
        int smallest = arr[0];
        int removeLocation=0;
        for(int i=0; i<size; i++){
            if(arr[i] < smallest){
                smallest = arr[i];
                removeLocation = i;
            }
        }
        for(int i=removeLocation; i<size; i++){
            arr[i] = arr[i+1];
        }
        if(smallestIndex == 1) {
            return smallest;
        } else return kthSmallest(arr, smallestIndex-1, size-1);
    }
}

public class Test {
    public static void main(String[] args){
        Func test = new Func();
        int number = test.kthSmallest(new int[]{3,1,2,4,5}, 2, 5);
        System.out.println(number);
    }
}

the result is

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5

I cannot find where that error is coming out.

Upvotes: 0

Views: 137

Answers (1)

Roushan
Roushan

Reputation: 4420

in second for loop you accessing the more out of range by i+1 modify as per below

for(int i=removeLocation; i<size-1; i++){
            arr[i] = arr[i+1];
        }

OUT

2

Upvotes: 1

Related Questions