For my programming class we need to write a method to find the median number in an array. I understand the basic concept that to find the median you just need to find the kth smallest number where 'k equals array.size/2', but I cannot get my code to work.
My task is to find the median of the first partition of the array. For this assignment we have to use the rightmost value as the pivot and the partition method has to return the index where the values are higher than the pivot.
Then we have to write a recursive method kthSmallest
method that has three cases:
- The size of the subarray of values smaller than the pivot is equal to k - this is the base case.
- The subarray of smaller values is larger than k-1 so the kth smallest is in the subarray of smaller values.
- The subarray of smaller values is smaller than k-1 so the kth smallest is in the subarray of larger values.
This is what I have so far, but I get
java.lang.ArrayIndexOutOfBoundsException: -1
in my partition method because for some reason end
is eventually -1
, so it tries to find arr[-1]
.
class Median{
static int kthSmallest(int[] arr, int left, int right, int k){
int divider = partition(arr, left, right);
if(divider == k-1){
System.out.println("Case1/Base");
return arr[divider];
}
if(divider > k-1){
System.out.println("Case2");
return kthSmallest(arr, left, divider, k);
}
else{
System.out.println("Case3");
return kthSmallest(arr, divider + 1, right, k - (divider +1));
}
}
static int partition(int[] arr, int left, int right){
int begin = left;
System.out.println("Begin: " + begin);
int end = right;
System.out.println("End: " + end);
int pivot = arr[right];
System.out.println("Pivot: " + pivot);
while(begin < end){
while(arr[begin] < pivot){
begin++;
}
while(arr[end] >= pivot){
end--;
}
swap(arr, begin, end);
}
swap(arr,begin,end);
System.out.println("return: " + begin);
printArr(arr);
return begin - 1;
}
static void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void printArr(int[] arr){
System.out.println();
for(int index = 0; index < arr.length - 1; index++){
System.out.print(arr[index] + ", ");
}
System.out.print(arr[arr.length-1]);
System.out.println();
}
public static void main(String[] args){
int[] arr = {34,-1,0,5,3};
printArr(arr);
//partition(arr, 0, 2);
//printArr(arr);
System.out.println(kthSmallest(arr, 0, arr.length - 1, 1));
}
}