Find the position of the given row in a 2 | C ++ implementation of the approach ; Function that compares both the arrays and returns - 1 , 0 and 1 accordingly ; Return 1 if mid row is less than arr [ ] ; Return 1 if mid row is greater than arr [ ] ; Both the arrays are equal ; Function to find a row in the given matrix using binary search ; If current row is equal to the given array then return the row number ; If arr [ ] is greater , ignore left half ; If arr [ ] is smaller , ignore right half ; No valid row found ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; const int m = 6 , n = 4 ; int compareRow ( int a1 [ ] , int a2 [ ] ) { for ( int i = 0 ; i < n ; i ++ ) { if ( a1 [ i ] < a2 [ i ] ) return 1 ; else if ( a1 [ i ] > a2 [ i ] ) return -1 ; } return 0 ; } int binaryCheck ( int ar [ ] [ n ] , int arr [ ] ) { int l = 0 , r = m - 1 ; while ( l <= r ) { int mid = ( l + r ) / 2 ; int temp = compareRow ( ar [ mid ] , arr ) ; if ( temp == 0 ) return mid + 1 ; else if ( temp == 1 ) l = mid + 1 ; else r = mid - 1 ; } return -1 ; } int main ( ) { int mat [ m ] [ n ] = { { 0 , 0 , 1 , 0 } , { 10 , 9 , 22 , 23 } , { 40 , 40 , 40 , 40 } , { 43 , 44 , 55 , 68 } , { 81 , 73 , 100 , 132 } , { 100 , 75 , 125 , 133 } } ; int row [ n ] = { 10 , 9 , 22 , 23 } ; cout << binaryCheck ( mat , row ) ; return 0 ; }