-
Notifications
You must be signed in to change notification settings - Fork 0
/
SearchInMatrix.java
53 lines (50 loc) · 1.52 KB
/
SearchInMatrix.java
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
import java.util.*;
public class SearchInMatrix {
public static int search(int[][] arr, int target)
{
{
// number of rows
int m = arr.length;
if(m == 0){
return -1;
}
// number of columns
int n = arr[0].length;
// binary search algorithm
int low = 0, high = m * n - 1;
int midIdx, midElement;
while(low <= high){
midIdx = low + (high - low)/2;
midElement = arr[midIdx / n][midIdx % n];
if(target == midElement){
return midIdx;
}
else{
if(target < midElement){
// left side
high = midIdx - 1;
}
else{
low = midIdx + 1;
}
}
}
return -1;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[][] = new int[3][3];
System.out.println("Enter the elements of the arr: ");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
arr[i][j] = sc.nextInt();
}
}
System.out.println("Enter the element to be searched: ");
int n = sc.nextInt();
int result = search(arr, n);
System.out.println("The element is present at: " + result);
sc.close();
}
}