Categories
Array Binary Search Leetcode Recursion

Search Matrix

let searchMatrix = function(matrix, target) {
if(!matrix.length) return false;

function search(startRow, endRow, startCol, endCol) {
console.log(startRow, endRow, startCol, endCol);
let midRow = Math.floor((startRow + endRow) / 2); //?
let midCol = Math.floor((startCol + endCol) / 2); //?


if (startRow < endRow && startCol < endCol) {
const midValue = matrix[midRow][midCol]; //?
if(midValue === target) {
return true;
}
if (midValue < target) {
return search(midRow + 1, endRow, startCol, endCol)
|| search(startRow, endRow, midCol + 1, endCol);
}
else {
return search(startRow, midRow, startCol, endCol)
|| search(startRow, endRow, startCol, midCol);
}
}

return false;
}

return search(0, matrix.length, 0, matrix[0].length);
};
Categories
Binary Search Recursion

Binary Search

function binarySearch(arr, n, start = 0, end = arr.length) {
let mid = Math.floor((end + start) / 2);
if (arr[mid] === n) return mid;

if (start < end - 1) {
if (n > arr[mid]) {
return binarySearch(arr, n, mid, end);
} else {
return binarySearch(arr, n, start, mid);
}
}
return -1;
}