Skip to content
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}