gpt4 book ai didi

java - 仅搜索第一列的按列排序二维数组的二进制搜索

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:42 24 4
gpt4 key购买 nike

所以我是编程新手,我正在尝试将二进制搜索算法应用于按列排序的二维数组。我的程序只在第一列上正确执行,所以我认为它陷入了无限循环。问题似乎出在我的 while 循环中的第二个 else-if 语句中,但我完全不知道问题出在哪里。

public static void main(String[] args) {
// TODO Auto-generated method stub

int[][] array = { {5, 8, 10, 6},
{20, 10, 20, 15},
{20, 15, 25, 20},
{20, 20, 32, 25} };
int query = 20;

int search_status;
search_status = count(array, query);
System.out.println(query + " occurred " + search_status + " times");

}

public static int count(int[][]array, int query){
int count = 0;
int low = 0;
int high = array.length - 1;
for (int c = 0; c < array[0].length; c++) {
while (low <= high) {
int mid = low + (high - low) / 2;

if (array[mid][c] > query) {
high = mid - 1;
}
else if (array[mid][c] < query) {
low = mid + 1;
}
else if (array[mid][c] == query) {
count++;
int up = -1;
int down = 1;
while ((mid + up >= 0) && (array[mid + up][c] == query)) {
up--;
count++;
}
while ((mid + down <= array.length - 1) && (array[mid + down][c] == query)) {
down++;
count++;
}
return count;
}
}
}
return - 1;
}

}

最佳答案

尝试这种先将列插入行的方法:

public static void main(String[] args) {
// TODO Auto-generated method stub

int[][] array = { {5, 8, 10, 6},
{20, 10, 20, 15},
{20, 15, 25, 20},
{20, 20, 32, 25} };
int query = 20;

int search_status = 0;

for (int c = 0; c < array.length; c++)
search_status += count(array, query, c);

System.out.println(query + " occurred " + search_status + " times");

}

public static int count(int[][]array, int query, int row){
int[] column = new int[array.length];
int count = 0;
int low = 0;
int high = column.length - 1;

for (int i = 0; i < array[row].length; i++)
column[i] = array[i][row];

while (low <= high) {
int mid = low + (high - low) / 2;

if (column[mid] > query) {
high = mid - 1;
}
else if (column[mid] < query) {
low = mid + 1;
}
else if (column[mid] == query) {
int mover = -1;
int counted = 1;

// Go all the way down
while ((mid + mover >= 0) && (column[mid + mover] == query))
{
mover--;
counted++;
}

mover+=counted+1;
count+=counted;

while ((mid + mover <= column.length - 1) && (column[mid + mover] == query))
{
mover++;
count++;
}

return count;
}
}

return 0;
}

编辑:稍微好一点的实现,以免重复计算。

关于java - 仅搜索第一列的按列排序二维数组的二进制搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33155389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com