理想情况下,我希望计数器在找到值后停止。当我运行程序时,它继续比较矩阵中的其他值。
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");
}
答案 0 :(得分:0)
if (matrix[row][col] == target)
{
found = true;
break; //Add this line
}
答案 1 :(得分:0)
如果布尔变量找到设置为false
,则永远不会进入while循环
它应该是:
while (!found)
并在found = true
后添加break
;
答案 2 :(得分:0)
您可以在break;
之后使用found = true
,但它会退出所有循环。如果只想退出for循环,则必须将&& !found
添加到for循环测试中。
while(!found)
?