Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

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

2 Answers

0 votes
#include <iostream>
 
bool matrix_search(int matrix[][5], int n, int* i, int* j) { 
    while (*i < n && *j >= 0) { 
        if (matrix[*i][*j] == n) { 
            return true;
        }
        if (matrix[*i][*j] > n) 
            (*j)--; 
        else
            (*i)++; 
    } 
     
    return false;
} 
    
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 (matrix_search(matrix, 37, &i, &j))
        std::cout << "Found: i = " << i << " j = " << j; 
    else
        std::cout << "Not found";
} 
  
  
 
  
/*
run:
  
Found: i = 2 j = 3
  
*/

 

 



answered May 13, 2019 by avibootz
edited Jun 22, 2023 by avibootz
0 votes
#include <iostream>
 
void matrix_search(int matrix[][5], int len, int n) { 
    int i = 0, j = len - 1; 
    while (i < n && j >= 0) { 
        if (matrix[i][j] == n) { 
            std::cout << "Found: i = " << i << " j = " << j; 
            return;
        }
        if (matrix[i][j] > n) 
            j--; 
        else
            i++; 
    } 
        
    std::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}, 
                       }; 
                      
    matrix_search(matrix, 5, 37); 
} 
 
 
 
 
/*
run:
 
Found: i = 2 j = 3
 
*/

 

 



answered May 13, 2019 by avibootz
edited Jun 22, 2023 by avibootz
...