forked from riya2001-cloud/java-hacktober
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMatrixBinarySearch.java
32 lines (27 loc) · 943 Bytes
/
MatrixBinarySearch.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
package BinarySearch;
import java.util.Arrays;
public class MatrixBinarySearch {
// Time Complexity = O(n)
// Reducing the search space to get the result
static int[] search(int[][] matrix, int target) {
int row = 0;
int column = matrix[0].length - 1; // matrix[0].length because it will handle 1D array also (corner case)
while(row < matrix.length && column >= 0) {
if(matrix[row][column] == target)
return new int[] {row,column};
if(matrix[row][column] < target)
row++;
else
column--;
}
return new int[] {-1,-1};
}
public static void main(String[] args) {
int[][] nums = { {10,20,30,40},
{15,25,35,45},
{28,29,37,49},
{33,34,38,50} };
int target = 37;
System.out.println(Arrays.toString(search(nums, target)));
}
}