# How to search for a number in sorted matrix with C++

4 views

```#include <iostream>

using namespace std;

int m_search(int matrix[][5], int n, int* i, int* j) {
while (*i < n && *j >= 0) {
if (matrix[*i][*j] == n) {
return 1;
}
if (matrix[*i][*j] > n)
(*j)--;
else
(*i)++;
}
return 0;
}

int main()
{
int matrix[5][5] = {{2, 3, 5, 7, 8},
{10, 13, 17, 18, 19},
{25, 26, 30, 37, 38},
{43, 46, 50, 51, 99},
};
int i = 0, j = 5;

if (m_search(matrix, 37, &i, &j))
cout << "Found: i = " << i << " j = " << j;
else

return 0;
}

/*
run:

Found: i = 2 j = 3

*/```

answered May 13 by
```#include <iostream>

using namespace std;

void m_search(int matrix[][5], int len, int n) {
int i = 0, j = len - 1;
while (i < n && j >= 0) {
if (matrix[i][j] == n) {
cout << "Found: i = " << i << " j = " << j;
return;
}
if (matrix[i][j] > n)
j--;
else
i++;
}

}

int main()
{
int matrix[5][5] = {{2, 3, 5, 7, 8},
{10, 13, 17, 18, 19},
{25, 26, 30, 37, 38},
{43, 46, 50, 51, 99},
};

m_search(matrix, 5, 37);

return 0;
}

/*
run:

Found: i = 2 j = 3

*/```

answered May 13 by