【发布时间】:2017-02-25 17:02:42
【问题描述】:
我对自己实现的二维数组的二进制搜索有点卡住了。它似乎没有迭代到下一行并保持在同一列中(因此是一个永无止境的循环)。二分搜索的工作方式是从两个端点(低端点和高端点)之间的中间开始。如果查询太低,则将高端点重新调整为中间点 - 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));
}
}
谢谢!
【问题讨论】:
-
二分搜索需要排序的数据。您的
array未排序。要计算数字 10 的实例,进行二进制搜索是没有意义的,您也可以在数组上进行 2D 循环,每次看到变量时 +1 到计数器 -
排序的是列,而不是行。
标签: java binary-search