1

I am getting an out of bounds exception thrown when I use this median of medians code to find a given location of k. I am not sure of the exact size at which it begins throwing the error, but the code works for arrays of size < 75, and the error starts when I exceed array size 100.

private static int mmQuickSortRecursive(Integer[] a, int k) {
    if (a.length <= 10)
    {
        Arrays.sort(a);
        return a[k-1];
    }
    int n = a.length;
    // partition L into subsets S[i] of five elements each (n/5 subsets).
    ArrayList<Integer[]> list = new ArrayList<Integer[]>();
    int cnt = 0;
    int m = n/5;
    for( int i = 0; i < m; i++ ) {
        Integer[] arr = new Integer[5];
        for( int j = 0; j < 5; j++ ) {
            if( cnt == n ) 
                break;
            arr[j] = a[cnt++];
        }
        Arrays.sort(arr);
        list.add(arr);
    }
    Integer[] x = new Integer[m];
    for (int i = 0; i< m; i++ ) {
        x[i] = list.get(i)[2];
    }
    int v = x[0];
    if(x.length > 2) {
                    ///////// ERROR THROWN ON BELOW LINE /////////////////
        v = (x.length%2 == 0)? x[x.length%2-1]: x[x.length/2];
    }
    //    partition L into 3 parts, L1<M, L2=M, L3>M
    Integer[] l = partition_left( a, v );
    Integer[] r = partition_right( a, v );
    if( k == l.length+1 ) {
        return v;
    } else if( k <= l.length ){
        return mmQuickSortRecursive(l,k);                               
    } else {
        return mmQuickSortRecursive(r,k-l.length-1);                            
    }       

}
Chris
  • 119
  • 8

1 Answers1

1
v = (x.length%2 == 0)? x[x.length%2-1]: x[x.length/2];

Seems wrong. shouldn't it be

v = (x.length%2 == 0)? x[x.length/2]: x[x.length/2-1];
Judge Mental
  • 5,209
  • 17
  • 22
  • That (x.length / 2 - 1) can also be -1 imho. – Gábor Bakos Mar 10 '14 at 22:47
  • This fixes the size issue, but the value for k being found by the method is not reciprocated by another find/sort method I am running on the same array. The code fix seems to give a value 4-5 values after the k I am looking for. – Chris Mar 10 '14 at 22:48
  • I saw that too. I think the logic _and_ the operator were backwards. – Judge Mental Mar 10 '14 at 22:48
  • Overall this is not a huge issue, if it finds a value near k for extremely large arrays this is fine, because the time to find it will be almost equivalent. I am using the method for large collections of time data, and it shouldn't screw that up at least. – Chris Mar 10 '14 at 22:49
  • Yes, after running the data for a few minutes, the values it returns are the correct ones often enough that it shouldn't skew my data. Even if there is another small error in there somewhere it should be fine. Thanks for the help! – Chris Mar 10 '14 at 22:54