-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBS_2D_Array_Sorted_Matrix.java
More file actions
75 lines (63 loc) · 2 KB
/
Copy pathBS_2D_Array_Sorted_Matrix.java
File metadata and controls
75 lines (63 loc) · 2 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package dsa;
import java.util.Arrays;
public class BS_2D_Array_Sorted_Matrix {
public static void main(String[] args) {
int[][] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(Arrays.toString(Search(arr,5)));
}
static int[] BinarySearch(int[][] matrix, int row, int cstart, int cend, int target) {
while (cstart <= cend) {
int mid = cstart + (cend - cstart) / 2;
if (matrix[row][mid] == target) {
return new int[]{row, mid};
}
if (matrix[row][mid] < target) {
cstart++;
} else {
cend--;
}
}
return new int[]{-1, -1};
}
static int[] Search(int[][] matrix, int target) {
int rows = matrix.length;
int cols = matrix[0].length;
if (cols == 0) {
return new int[]{-1, -1};
}
if (rows == 1) {
return BinarySearch(matrix, 0, 0, cols - 1, target);
}
int rStart=0;
int rEnd=rows-1;
int cMid=cols/2;
while (rStart<=(rEnd-1)){
int mid=rStart+(rEnd-rStart)/2;
if (matrix[mid][cMid]==target){
return new int[]{mid,cMid};
}
if (matrix[mid][cMid]<target){
rStart=mid;
}
else {
rEnd=mid;
}
}
if (target<=matrix[rStart][cMid-1]){
return BinarySearch(matrix,rStart,0,cMid-1,target);
}
if (target>=matrix[rStart][cMid+1]){
return BinarySearch(matrix,rStart,cMid+1,cols-1,target);
}
if (target<=matrix[rStart+1][cMid-1]){
return BinarySearch(matrix,rStart+1,0,cMid-1,target);}
if (target>=matrix[rStart][cMid+1]){
return BinarySearch(matrix,rStart+1,0,cMid+1,target);
}
return new int[]{-1,-1};
}
}