Wednesday 30 April 2014

searching an element in two dimensional sorted array

PSEUDOCODE












CODE


int search(int mat[4][4], int n, int x)
{
   int row = 0, column = n-1;  //set indexes for top right element
   while ( row < n && column >= 0 )
   {
      if ( mat[row][column] == x )
      {
         printf("\n %d Found at %d, %d",x, row, column);
         return 1;
      }
      if ( mat[row][column] > searchElement )
        column--;
      else //  if matrix[row][column] < x
        row++;
   }
   printf("\n Element not found");
   return 0;  // if ( row==n || column== -1 )
}

int main()
{
  int matrix[4][4] = { {10, 20, 30, 40},
                     {15, 25, 35, 45},
                     {27, 29, 37, 48},
                     {32, 33, 39, 50},
                   };
  search(matrix, 4, 29);
  getchar();
  return 0;
}