#include <iostream>
using namespace std;
//row-wise binary search.
int search2DArray(int matrix[][4], int n, int m, int key){
int start = 0, end = m-1;
for(int i=0; i<n; i++){
while(start<=end){
int mid = (start+end)/2;
if(matrix[i][mid] == key){
cout<<"FOUND\n";
return 0;
}else if(matrix[i][mid] < key){
start = mid + 1;
}else{
end = mid - 1;
}
}
}
cout<<"NOT FOUND\n";
return -1;
}
int main(){
int matrix[4][4] = {{10,20,30,40},
{15,25,35,45},
{27,29,37,48},
{32,33,39,50}};
search2DArray(matrix, 4, 4, 29);
return 0;
}
我尝试应用 for 循环来迭代 2D 数组的所有行,但无法超过第一行,并且对于行 > 0 的任何输入始终打印 NOT FOUND。
当您完成一行时,您忽略了重置
start
和 end
,因此下一行以 start
和 end
开始,处于退出状态。
int search2DArray(int matrix[][4], int n, int m, int key){
// int start = 0, end = m-1; <<-- move this line
for(int i=0; i<n; i++){
int start = 0, end = m-1; // <<-- to here
while(start<=end){
int mid = (start+end)/2;
if(matrix[i][mid] == key){
cout<<"FOUND\n";
return 0;
}else if(matrix[i][mid] < key){
start = mid + 1;
}else{
end = mid - 1;
}
}
}
cout<<"NOT FOUND\n";
return -1;
}