diff --git a/lectures/10-binary search/code/src/com/kunal/SortedMatrix.java b/lectures/10-binary search/code/src/com/kunal/SortedMatrix.java index f1ba1f9b6..76f069f22 100644 --- a/lectures/10-binary search/code/src/com/kunal/SortedMatrix.java +++ b/lectures/10-binary search/code/src/com/kunal/SortedMatrix.java @@ -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); } }