Saddleback Search Algorithm in a 2D array | C ++ program to search an element in row - wise and column - wise sorted matrix ; Searches the element x in mat [ m ] [ n ] . If the element is found , then prints its position and returns true , otherwise prints " not ▁ found " and returns false ; set indexes for bottom left element ; if mat [ i ] [ j ] < x ; driver program to test above function
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  100 NEW_LINE bool search ( int mat [ ] [ MAX ] , int m , int n , int x ) { int i = m - 1 , j = 0 ; while ( i >= 0 && j < n ) { if ( mat [ i ] [ j ] == x ) return true ; if ( mat [ i ] [ j ] > x ) i -- ; else j ++ ; } return false ; } int main ( ) { int mat [ ] [ MAX ] = { { 10 , 20 , 30 , 40 } , { 15 , 25 , 35 , 45 } , { 27 , 29 , 37 , 48 } , { 32 , 33 , 39 , 50 } , { 50 , 60 , 70 , 80 } , } ; if ( search ( mat , 5 , 4 , 29 ) ) cout << " Yes " ; else cout << " No " ; return 0 ; }