How to search for a number in a sorted matrix in JavaScript

1 Answer

0 votes
function searchMatrix(matrix, target) {
    const rows = matrix.length;
    const cols = matrix[0].length;

    let row = 0;
    let col = cols - 1;

    while (row < rows && col >= 0) {
        const value = matrix[row][col];
        if (value === target) {
            console.log(`Found: i = ${row} j = ${col}`);
            return true;
        } else if (value > target) {
            col--;
        } else {
            row++;
        }
    }

    console.log("Not found");
    return false;
}

const matrix = [
    [2, 3, 5, 7, 8],
    [10, 13, 17, 18, 19],
    [25, 26, 30, 37, 38],
    [43, 46, 50, 51, 99]
];

searchMatrix(matrix, 37);



/*
run:

Found: i = 2 j = 3

*/

 



answered 15 hours ago by avibootz
...