From 3ea7756782ec20ea7e3571b9882d574908bd4881 Mon Sep 17 00:00:00 2001 From: Rajat Yadav Date: Sun, 22 Mar 2026 22:17:05 +0530 Subject: [PATCH] Fixed : Edge checks for cMid preventing it from getting index out of bounds. --- .../code/src/com/kunal/SortedMatrix.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) 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); } }