From 27c8eee8d6b9e74f2dbe9fc4ca0ef1222c5b330c Mon Sep 17 00:00:00 2001 From: Aditya Kulkarni <213192267+Aditya2375@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:19:08 +0530 Subject: [PATCH] fix: stop BinarySearch2dArray crashing on two-column matrices --- .../searches/BinarySearch2dArray.java | 5 +-- .../searches/BinarySearch2dArrayTest.java | 32 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java index 317db0dead05..f87c03f45c5a 100644 --- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java +++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java @@ -82,8 +82,9 @@ else if (arr[midRow][midCol] < target) { } // If target is between midCol and the last column of startRow, perform a binary - // search on that part of the row. - if (target >= arr[startRow][midCol + 1] && target <= arr[startRow][colCount - 1]) { + // search on that part of the row. When the matrix has only two columns, midCol is + // the last column and there is no right side to search. + if (midCol + 1 < colCount && target >= arr[startRow][midCol + 1] && target <= arr[startRow][colCount - 1]) { return binarySearch(arr, target, startRow, midCol + 1, colCount - 1); } diff --git a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java index 236e1be5cc23..1d9204295fb3 100644 --- a/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java +++ b/src/test/java/com/thealgorithms/searches/BinarySearch2dArrayTest.java @@ -203,4 +203,36 @@ public void binarySearch2dArrayTestSingleElementNotFound() { int[] ans = BinarySearch2dArray.binarySearch(arr, target); assertArrayEquals(new int[] {-1, -1}, ans); } + + @Test + public void binarySearch2dArrayTestTwoColumnsTargetInFirstColumn() { + int[][] arr = {{9, 23}, {26, 30}}; + int target = 26; + int[] ans = BinarySearch2dArray.binarySearch(arr, target); + assertArrayEquals(new int[] {1, 0}, ans); + } + + @Test + public void binarySearch2dArrayTestTwoColumnsTargetNotFound() { + int[][] arr = {{9, 23}, {26, 30}}; + int target = 28; + int[] ans = BinarySearch2dArray.binarySearch(arr, target); + assertArrayEquals(new int[] {-1, -1}, ans); + } + + @Test + public void binarySearch2dArrayTestTwoColumnsLargerMatrix() { + int[][] arr = {{1, 4}, {5, 8}, {9, 12}, {13, 16}}; + int target = 13; + int[] ans = BinarySearch2dArray.binarySearch(arr, target); + assertArrayEquals(new int[] {3, 0}, ans); + } + + @Test + public void binarySearch2dArrayTestTargetInValueGap() { + int[][] arr = {{1, 5, 9}, {10, 14, 18}, {20, 24, 28}}; + int target = 7; + int[] ans = BinarySearch2dArray.binarySearch(arr, target); + assertArrayEquals(new int[] {-1, -1}, ans); + } }