forked from KISHOREMUTHU/Data-Structures-And-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrix_binary_search.c
More file actions
60 lines (33 loc) · 980 Bytes
/
Copy pathmatrix_binary_search.c
File metadata and controls
60 lines (33 loc) · 980 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Data-Structures-And-Algorithms
Here I will post my regular DSA problems
//Matrix binary search
#include <stdio.h>
#include<string.h>
int main (){
int a[3][3]; // 3x3 matrix for an example . If you wan , you can take any input matrix
int i,j,x,l,r,mid,mid_el; // mid - middle value , mid_el - exact matrix equivalent value of mid
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
scanf ("%d",&a[i][j]);
}
}
scanf ("%d",&x);
l=0;
r=8;
// Binary Search method
while (l<=r){
mid=(l+r)/2;
mid_el=a[mid/3][mid%3]; // Formula to find the equivalent mid element in the matrix
if(mid_el==x){
printf("%d",mid_el);
break;
}
else if(mid_el<x){
r=mid-1;
}
else{
l=mid+1;
}
}
return 0 ;
}