0

Working on a method that picks a pivot for finding the kth smallest element in an array using median of medians algorithm; however it doesn't seem to exit pickCleverPivot after the return:

return median(A,left,right);

If it helps, assume that initially left is 0, right is 9, and A is {1,2,3,4,5,6,7,8,9,10}.

Here's the method:

private static int pickCleverPivot(int left, int right, int[] A){

    int index = 0;                                                  
    if((right-left) <= 5){                                          
        return median(A,left,right);
    }

    for(int i = 0; i < (A.length+5-1)/5; i++){      //Ceiling of n/5 = (A.length+5-1)/5). 

        int R = left+4;  
        if(R > right){
            R = right;                                              
        }

        int med_index = median_index(A,left,R);

        swap(A, med_index, index);
        index++;
        left +=5;
    }

    left = 0;
    return pickCleverPivot(left, left+(A.length+5-1)/5, A);

}
  • Umm, if your lft is 0 and right is 9, right - left = 9 & it's > 5, so it won't enter that return statement, yes? So then, it'll continue down to where it calls median_index and swap, which might be the bottleneck. – Aaa Sep 30 '16 at 18:50

3 Answers3

3

There should be no way for your code to ignore a return statement.

Maybe you created an infinite loop? If you want to find an error in you code, just add a lot of print statements. For example print the returned values of all methods, before returning them.

If you still cant find your error, you should post all of your code, so we are able to run your code by ourself.

Mein Name
  • 527
  • 3
  • 14
0

I'd say, go for a step-by-step debugging, most probably, there is an infinite loop which is causing the return to stop returning from the method. Or else, do paste the complete code, I can try finding the bug.

Atul Kumar
  • 421
  • 3
  • 12
0

I think I found something :

Each time you make a recursive call to your function, it's with the same parameters. (A.length+5-1)/5 remains the same value because A is always the same array. So if it is greater than 5, you never escape your recursive function, because right - left < 5 will always be false.

Bycob
  • 34
  • 3