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,851 questions

51,772 answers

573 users

How to search for a number in sorted matrix with C

2 Answers

0 votes
#include <stdio.h>

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) { 
            printf("Found: i = %d j = %d", i, j); 
            return;
        }
        if (matrix[i][j] > n) 
            j--; 
        else 
            i++; 
    } 
      
    printf("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, 2019 by avibootz
0 votes
#include <stdio.h>

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))
        printf("Found: i = %d j = %d\n", i, j); 
    else
        printf("Not found\n");

    return 0; 
} 


/*
run:

Found: i = 2 j = 3

*/

 



answered May 13, 2019 by avibootz
...