In: Computer Science
C programming problem
I have to design an efficient algorithm which solves this
problem. Also, it needs to include time and space complexities of
this algorithm.
There is a matrix (N times N) of integers which rows and columns
are sorted in non-decreasing order.
A sorted matrix and integer M will be given and we need to find the
position(row,column) of M in this matrix. it's okay to report only
one position if there are more than one answers.
when it is 4 times 4 matrix, and integer M is 19
2 | 29 | 37 | 60 |
9 | 11 | 33 | 87 |
19 | 35 | 17 | 5 |
22 | 15 | 91 | 7 |
the answer will be (3,1)
I need to find an efficient way to find this position
CODE IN C:
#include <stdio.h>
int main()
{
int n;
printf("Enter the size of the square matrix:");
scanf("%d",&n);
int mat[n][n];
printf("Enter the elements of the matrix:");
int i,j;
for(i=0;i<n;i++){
for(j=0;j<n;j++){
scanf("%d",&mat[i][j]);
}
}
printf("below is your matrix:\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
printf("%d ",mat[i][j]);
}
printf("\n");
}
int row=0,column=0,number;
printf("Enter an integer:");
scanf("%d",&number);
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(mat[i][j]==number){
row = i+1;
column = j+1;
}
}
}
if(row==0)
printf("\nSorry... Your number didnt exist in your
matrix...");
else
printf("\nYour number found at the position
(%d,%d)",row,column);
return 0;
}
OUTPUT: