Locating a value in a row- and column-sorted grid
Question
An matrix has every row sorted increasing from left to right and every column sorted increasing from top to bottom. How do you search it for a given value, and what is the cost?
Short answer
Start at the top-right corner: . If the entry equals the target you are done; if it is larger, move left (everything below in that column is larger too); if smaller, move down (everything left in that row is smaller). Each step discards a whole row or column, so at most steps are needed.
Adapted from Zhou, A Practical Guide to Quantitative Finance Interviews, sec. 7.1 Algorithms, 'Search algorithm C', p.177; question and answer rewritten by SelfMadeQuant.com.
See the hint and the full worked solution in the question bank (free account).
Open the worked solution