當我被分配到寫算法,從無序組數字的發現K-階數一門功課的中位數。作爲一種方法,已經提出了算法median of medians
。選擇:中位數
不幸的是,我學嘗試已經失敗。如果有人發現錯誤 - 請糾正我。
private int find(int[] A, int size, int k) {
if (size <= 10) {
sort(A, 0, size);
return A[k];
} else {
int[] M = new int[size/5];
for (int i = 0; i < size/5; i++) {
sort(A, i*5, (i+1) * 5);
M[i] = A[i*5 + 2];
}
int m = find(M, M.length, M.length/2);
int[] aMinus = new int[size];
int aMinusIndex = 0;
int[] aEqual = new int[size];
int aEqualIndex = 0;
int[] aPlus = new int[size];
int aPlusIndex = 0;
for (int j = 0; j < size; j++) {
if (A[j] < m) {
aMinus[aMinusIndex++] = A[j];
} else if (A[j] == m) {
aEqual[aEqualIndex++] = A[j];
} else {
aPlus[aPlusIndex++] = A[j];
}
}
if (aMinusIndex <= k) {
return find(aMinus, aMinusIndex, k);
} else if (aMinusIndex + aEqualIndex <= k) {
return m;
} else {
return find(aPlus, aPlusIndex, k - aMinusIndex - aEqualIndex);
}
}
}
private void sort(int[] t, int begin, int end) { //simple insertion sort
for (int i = begin; i < end; i++) {
int j = i;
int element = t[i];
while ((j > begin) && (t[j - 1] > element)) {
t[j] = t[j - 1];
j--;
}
t[j] = element;
}
}
我跑的測試是把數字{200,199,198,...,1),並得到有序排列的第一個數字。我越來越:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -13
這是在return A[k]
行拋出,因爲遞歸調用,:
return find(aPlus, aPlusIndex, k - aMinusIndex - aEqualIndex);
您是否嘗試過在調試器中運行你的代碼? – 2013-05-06 21:06:47
你確定你的輸入和輸出關係嗎? – 2013-05-06 21:51:14