-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchValueinMatrix.java
More file actions
59 lines (52 loc) · 1.89 KB
/
Copy pathSearchValueinMatrix.java
File metadata and controls
59 lines (52 loc) · 1.89 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
import java.util.Scanner;
public class SearchValueinMatrix {
public static void main(String[] args) {
// Initialize the 'target' value for searching
int target = 0;
// Create a 3x3 matrix and populate it with values
int[][] matrix = new int[3][3];
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
matrix[row][col] = (1 + row * 3 + col);
}
}
// Display the contents of the matrix
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
System.out.print(matrix[row][col] + " ");
if (col == 2) {
System.out.println();
}
}
}
// Print the result of the 'searchMatrix' function
System.out.print(Boolean.toString(searchMatrix(matrix, target)));
}
public static boolean searchMatrix(int[][] matrix, int target) {
// Check if the matrix is empty or has no columns
if (matrix.length == 0 || matrix[0].length == 0) {
return false;
}
// Get the number of rows 'm' and columns 'n' in the matrix
int m = matrix.length;
int n = matrix[0].length;
// Initialize 'lower' and 'higher' for binary search
int lower = 0;
int higher = m * n - 1;
// Perform binary search to find 'target' in the matrix
while (lower <= higher) {
int mid = (lower + higher) >> 1;
int val = matrix[mid / n][mid % n];
if (val == target) {
return true;
}
if (val < target) {
lower = mid + 1;
} else {
higher = mid - 1;
}
}
// If 'target' is not found, return false
return false;
}
}