Home C Language Basic C Programs Search in a Row wise and Column wise Sorted Matrix

Search in a Row wise and Column wise Sorted Matrix


Write a program in C to search an element in a row wise and column wise sorted matrix.

#include <stdio.h>

void main()

{

   int a[10][10],n,m,i,j,x;

   printf(“Enter sixe of matrix:\n”);

   scanf(“%d%d”,&n,&m);

   printf(“Enter the elements of matrix:\n”);

   for(i=0;i<n;i++)

   for(j=0;j<m;j++)

      scanf(“%d”,&a[i][j]);

   printf(“Enter the search element: “);

   scanf(“%d”,&x);

   i=0;

   j=m-1;

   while(i<n&&j>=0)

   {

      if(a[i][j]==x)

      {

         printf(“Element is found at %d, %d\n”,i+1,j+1);

         return;

      }

      if(a[i][j]<x)

         i++;

      else

         j- -;

   }

   printf(“Element is not found\n”);

}

Output:

Enter size of matrix:

3              3

Enter the elements of matrix:

12           25           37

41           46           55

61           75           82

Enter the search element: 47

Element is not found.