gpt4 book ai didi

java - 排序列表的二维数组线性搜索

转载 作者:太空宇宙 更新时间:2023-11-04 12:47:16 25 4
gpt4 key购买 nike

理想情况下,我希望计数器在找到该值后停止。当我运行该程序时,它继续比较矩阵中的其他值。

public static void LinearSearch1(int[][] matrix, int array_size, int target) {
int row, col;
int comparison_counter = 0;
boolean found = false;

while (!found)
{
for (row = 0; row < array_size; row++)
{

for (col = 0; col < array_size; col++)
{
comparison_counter++;
if (matrix[row][col] == target)
{
found = true;

}//end if


}//end inner for
}//end outer for
} //end while

System.out.println(target + " found in " + comparison_counter + " number of comparisons using linear search");
}

最佳答案

您可以在 found = true 之后使用 break;,但它将退出所有循环。如果您只想退出 for 循环,则必须将 && !found 添加到 for 循环测试中。

顺便说一句,为什么你有一个while(!found)

关于java - 排序列表的二维数组线性搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36185500/

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