I wonder, can binary search be applied on a 2D array?
Just pretend it's a 1D array and calculate the correct row and column as you divide and conquer:
/**
* @param grid {[[number]]} A 2D NxM grid of numbers
* @param targetValue {number} The target value to search
* @return {[number]} A list containing the row and column. For example, [0,5] means row 0 column 5
*/
function search (grid, targetValue) {
let rows = grid.length;
let cols = grid[0].length;
let leftBound = 0;
let rightBound = rows * cols - 1;
while (true) {
let currentIndex = parseInt((leftBound + rightBound) / 2);
let currentRow = parseInt(currentIndex / cols);
let currentColumn = currentIndex % cols;
let currentValue = grid[currentRow][currentColumn];
if (currentValue === targetValue) {
return [currentRow, currentColumn];
}
else if (rightBound <= leftBound) {
return [-1, -1];
}
else if (currentValue < targetValue) {
leftBound = currentIndex + 1;
}
else {
rightBound = currentIndex - 1;
}
}
}
search([[11,12,15,23],[25,28,31,32],[35,45,47,47],[50,51,55,56],[65,65,78,88]], 45);