0
我有點卡在我自己的2D數組二進制搜索的實現。它似乎沒有迭代到下一行並保留在同一列(因此是一個永無止境的循環)。二進制搜索的工作方式是從兩個端點(低端和高端點)之間的中間開始。如果查詢太低,則將高端點重新調整爲中點 - 1.如果查詢太高,則將低端點設置爲中點端點+1。所有這些都會發生,直到查詢被找到,或者沒有匹配,從而導致O(log n)的最壞情況。但是,我似乎無法讓數組逐行去搜索值。這是我迄今爲止所做的:卡住 - 我自己實現的多維二進制搜索
public static int count(int[][]array, int query) {
int countoccurences = 0;
int low = 0;
int high = array[0].length - 1;
for (int row = 0; row < array.length; row++) {
for (int column = 0; column < array[row].length; column++) {
while (low <= high) {
int mid = (low + high)/2; //Set mid point to be (low + high) divided by 2
if (array[row][mid] == query) { //Check if middle value in each column is equal to the search query
countoccurences++; //If it is, increment countoccurences by 1
} else if (array[row][mid] < query) {
low = mid + 1; //If it is less than query then re-adjust low to be mid index + 1
} else {
high = mid - 1; //if query is too low, re-adjust high to be mid index - 1
}
}
}
}
return countoccurences;
}
public static void main(String[] args) {
int[][] array = { {7, 4, 3, 5, 10},{8, 5, 4, 6, 11},{10, 10, 8, 10, 13}, {11, 10, 15, 10, 14}};
System.out.println("Total occurences of the number 10 is: " + count(array, 10));
}
}
謝謝!
二進制搜索需要排序的數據。你的數組沒有排序。爲了統計數字10的實例,進行二分搜索沒有意義,您最好在數組上進行2D循環,並在每次看到變量時對計數器+1, –
這是已排序的列,並且而不是行。 – pr0grammeur