当我使用这个中位数代码来查找k的给定位置时,我得到一个超出范围的异常。我不确定它开始抛出错误的确切大小,但代码适用于大小< 75,当我超过数组大小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);
}
}
答案 0 :(得分:1)
v = (x.length%2 == 0)? x[x.length%2-1]: x[x.length/2];
似乎错了。不应该是
v = (x.length%2 == 0)? x[x.length/2]: x[x.length/2-1];