-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathBinarySearchin2d.java
More file actions
26 lines (24 loc) · 829 Bytes
/
Copy pathBinarySearchin2d.java
File metadata and controls
26 lines (24 loc) · 829 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
import java.util.Arrays;
public class BinarySearchin2d {
public static void main(String[] args) {
// A sample 2d array
int[][] arr = { { 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 28, 29, 37, 49 },
{ 33, 34, 38, 40 } };
System.out.println(Arrays.toString(search(arr, 37)));
}
static int[] search(int[][] array, int target) {
int row = 0, col = array.length - 1;
while (row < array.length || col >= 0) {
if (array[row][col] == target) {
return new int[] { row, col }; // Element found
} else if (array[row][col] > target) {
col--;
} else {
row++;
}
}
return new int[] { -1, -1 }; // Element not found
}
}