Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Given a matrix of size NxM sorted in descending order and value V, write a funct

ID: 3855255 • Letter: G

Question

Given a matrix of size NxM sorted in descending order and value V, write a function which returns -1 if value V is not in the matrix, else it returns 1 if V is in the matrix. The function also computes the position of V in the matrix, that is P= [R, C], where R is the row number of V and C is the column number of V in the matrix, if V is in the matrix (if V is not in the matrix then P=[-1,-1]); P is a 1D array of size 2. You must use the recursive Binary Search method.

int SearchMatrix(int A[ ] [ ], int V, int *P, unsigned int rowsize, unsigned int colsize);

NOTE:

#define COL 20

#define ROW 20

Explanation / Answer

#include<stdio.h>


int binarySearch(int Mat[4][4],int row,int first,int last,int target)
{
int middle= (first+last)/2;
  
if(first>last)
return -1;

if(Mat[row][middle]==target)
return middle;
  
if(Mat[row][middle]>target)
return binarySearch(Mat,row,first,middle-1,target);
  
return binarySearch(Mat,row,middle+1,last,target);
}
int binarySearchRow(int Mat[4][4],int first,int last,int size,int target)
{
if(first>last)
return -1;

int middle= (first+last)/2;
if(Mat[middle][0]<= target && Mat[middle][size-1]>=target)
return middle;
  
if(Mat[middle][0]>target)
return binarySearchRow(Mat,first,middle-1,size,target);
  
return binarySearchRow(Mat,middle+1,last,size,target);
}
int search(int Mat[4][4],int target,int *p,int x,int y)
{
x= binarySearchRow(Mat,0,4,4,target);

if(x==-1)

return 0;
  
y = binarySearch(Mat,x,0,4,target);
if(y==-1)
return 0;
  
*p=x;
p++;
*p=y;
return 1;
}

int main()
{
int mat[4][4] = { {10, 4, 4, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50},
};
int x,y;
int p[2]={-1,-1};
printf("Element 37 is found at ");

search(mat,37,p ,x,y);
printf("%d %d ",p[0],p[1]);
return 0;
}

================================================================

Output:

akshay@akshay-Inspiron-3537:~/Chegg$ gcc bstre.c
akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
Element 37 is found at
2 2

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote