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

1 Answer

0 votes
def search_matrix(matrix, target):
    rows = len(matrix)
    cols = len(matrix[0])

    row, col = 0, cols - 1

    while row < rows and col >= 0:
        value = matrix[row][col]
        if value == target:
            print(f"Found: i = {row} j = {col}")
            return True
        elif value > target:
            col -= 1
        else:
            row += 1

    print("Not found")
    return False


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

search_matrix(matrix, 37)



"""
run:

Found: i = 2 j = 3

"""

 



answered 1 day ago by avibootz
...