Skip to content

Commit 737d53c

Browse files
committed
search element in 2D matrix
1 parent bbdfe40 commit 737d53c

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package Lecture14;
2+
3+
public class searchMatrix2 {
4+
5+
public static void main(String[] args) {
6+
7+
int[][] arr = { { 10, 20, 30, 40 },
8+
{ 11, 21, 31, 41 },
9+
{ 12, 22, 32, 42 },
10+
{ 13, 23, 33, 43 } };
11+
12+
System.out.println(searchKeyMatrix(arr, 22)); // true
13+
System.out.println(searchKeyMatrix(arr, 10)); // true
14+
System.out.println(searchKeyMatrix(arr, 42)); // true
15+
System.out.println(searchKeyMatrix(arr, 23)); // true
16+
System.out.println(searchKeyMatrix(arr, 13)); // true
17+
System.out.println(searchKeyMatrix(arr, 2)); // false
18+
19+
}
20+
21+
public static boolean searchKeyMatrix(int[][] arr, int key) {
22+
int start = 0, end = arr.length - 1;
23+
int mid = (start + end) / 2;
24+
if (arr[0][mid] == key || arr[mid][0] == key) {
25+
return true;
26+
}
27+
28+
int startcol = 0;
29+
int endcol = arr.length - 1;
30+
if (key < arr[0][mid]) {
31+
endcol = mid;
32+
} else {
33+
startcol = mid;
34+
}
35+
36+
int startrow = 0;
37+
int endrow = arr.length - 1;
38+
if (key < arr[mid][0]) {
39+
endrow = mid;
40+
} else {
41+
startrow = mid;
42+
}
43+
for (int row = startrow; row <= endrow; row++) {
44+
for (int col = startcol; col <= endcol; col++) {
45+
if (arr[row][col] == key) {
46+
return true;
47+
}
48+
}
49+
}
50+
return false;
51+
}
52+
}

0 commit comments

Comments
 (0)