Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions lectures/10-binary search/code/src/com/kunal/SortedMatrix.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,24 @@ static int[] search(int[][] matrix, int target) {
return new int[]{rStart + 1, cMid};
}

// rEnd = rStart+1 (this will cause no error)

/*
Introducing edge checks for cMid so that it does not get out of bounds.
*/
// search in 1st half
if (target <= matrix[rStart][cMid - 1]) {
if (cMid > 0 && target <= matrix[rStart][cMid - 1]) {
return binarySearch(matrix, rStart, 0, cMid-1, target);
}
// search in 2nd half
if (target >= matrix[rStart][cMid + 1] && target <= matrix[rStart][cols - 1]) {
if (cMid < cols - 1 && target >= matrix[rStart][cMid + 1] && target <= matrix[rStart][cols - 1]) {
return binarySearch(matrix, rStart, cMid + 1, cols - 1, target);
}
// search in 3rd half
if (target <= matrix[rStart + 1][cMid - 1]) {
if (cMid > 0 && target <= matrix[rStart + 1][cMid - 1]) {
return binarySearch(matrix, rStart + 1, 0, cMid-1, target);
} else {
}
else {
return binarySearch(matrix, rStart + 1, cMid + 1, cols - 1, target);
}
}
Expand Down