Closed
Description
Description
- I've identified a bug in the
RowColumnWiseSorted2dArrayBinarySearch.java
implementation. - The column pointer (colPointer) is initialized using
matrix.length - 1
. But, matrix.length returns the number of rows, not the number of columns. - This causes the algorithm's starting point to be incorrect for any matrix that is not square.
- The problematic line is:
// in src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java
int colPointer = matrix.length - 1; // The pointer at end column
Steps to reproduce
- The bug can be reproduced with any non-square matrix where the number of rows and columns are different.
- For example, with a 2x4 matrix:
1 int[][] matrix = {
2 {10, 20, 30, 40},
3 {15, 25, 35, 45}
4 };
- With the current code, matrix.length is 2, so colPointer is initialized to 1.
- The search incorrectly starts at matrix[0][1] (value 20) instead of the top-right corner matrix[0][3] (value 40).
Excepted behavior
- The colPointer should be initialized to the index of the last column, allowing the search to correctly start at the top-right corner of the matrix. The correct initialization should be:
int colPointer = matrix[0].length - 1;
Screenshots
No response
Additional context
I would like to submit a Pull Request to fix this initialization issue.