# Working C++ soln but have doubt

#1

This soln. works perfectly fine. But when I implement the binary search manually by iterating over the matrix elements, finding mid, etc, I’m getting errors. Can someone post a soln with the working manual bin search please?

``````int Solution::searchMatrix(vector<vector<int> > &A, int B) {
int r = A.size();
int c = A[0].size();
int ind = 0;

for(int i = 0; i<r; i++){
if(A[i][c-1] == B || A[i][0] == B) return 1;
else if(A[i][c-1] > B && A[i][0] < B){
ind = i;
break;
}
}
if(binary_search(A[ind].begin(), A[ind].end(), B)) return 1;
else return 0;
}``````

#2

int binary(vector<vector >arr, int x,int row,int s,int e){
if(s<=e){
int mid = (s+e)/2;
if(arr[row][mid]==x){
return 1;
}
else if(arr[row][mid]>x){
return binary(arr,x,row,s,mid-1);
}
else{
return binary(arr,x,row,mid+1,e);
}
}
return 0;
}
int Solution::searchMatrix(vector<vector > &arr, int b) {
int row = arr.size();
int col = arr[0].size();
int poss_row;
//find row containing range of b
for(int i=0;i<row;i++){
if(arr[i][col-1]>b){
poss_row = i;
break;
}
if(arr[i][col-1]==b){
return 1;
}
}
// apply binary search in poss_row
return binary(arr,b,poss_row,0,col-1);
}