Why my for loop is not iterating to the rows in 2D array ?
#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<<"FOUNDn";
return 0;
}else if(matrix[i][mid] < key){
start = mid + 1;
}else{
end = mid - 1;
}
}
}
cout<<"NOT FOUNDn";
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;
}
I tried to apply for loop to iterate all the rows of 2D array but couldn’t get past the first row and always printing NOT FOUND for any input for row > 0.
New contributor
Himanshu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.