public class MatrixSearch {
public static void main(String[] args) {
int[][] mat = {
{10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50}
};
int X = 37;
System.out.println(searchInSortedMatrix(mat, X));
}
public static int searchInSortedMatrix(int[][] mat, int X) {
for (int i = 0; i < mat.length; i++) {
if((X >= mat[i][0]) && (X <= mat[i][mat[i].length - 1])) {
return binarySearch(mat[i], X);
}
}
return 0;
}
public static int binarySearch(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
while (low <= high) {
int mid = (low + high) / 2;
System.out.println("low: " + low + ", high: " + high + ", mid: " + mid);
System.out.println(target);
if (arr[mid] == target) {
return 1; // Target found, return 1
} else if (target > arr[mid]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return 0; // Target not found, return 0
}
}
in the searchInSortedMatrix() method the for loop sends the first row of the matrix to binarysearch() method instead of sending the third row where 37 is present.the code must return 1, but it returns 0. can someone please help me with this :)?
10 20 30 40 --> loop sent to the binarysearch() method
In searchInSortedMatrix method, you are returning the answer irrespective of whether you found the answer in the first row or not.
searchInSortedMatrix terminates and returns 0 after checking first row(in your case, as you are searching for 37) and it doesnot go on for checking other rows.
You can change it like this, to return 1 inside the loop, only when you find the element in corresponding row.