Welcome to collectivesolver - Programming & Software Q&A. A website you can trust. All programs tested and works. Contact: aviboots(AT)netvision.net.il
Bonsai Boy of New York Bonsai Trees and Accessories

BlueHost Web Hosting

Liquid Web iThemes WordPress Hosting

Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

DreamHost Web Hosting


Ecommerce Software - Best Ecommerce Platform Made for You - Free Trial

Liquid Web Cloud VPS Hosting

10,935 questions

14,843 answers

573 users

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

2 Answers

0 votes
#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
        cout << "Not found";

    return 0; 
} 


/*
run:

Found: i = 2 j = 3

*/

 




answered May 13 by avibootz
0 votes
#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++; 
    } 
       
    cout << "Not found";
} 
   
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 avibootz
...