find an element in a sorted matrix [duplicate]

Start in the bottom-left corner of your matrix. Then go to the right until you find the exact number (done), or until you find a number that is bigger.

Then you go upwards in the matrix until you find the exact number (done), or until you find a number that is too small.

Then again you move to the right, … and so on until you found the number or until you reach the right-side or top of your matrix.

The following images contain some examples, using an Excel table showing the target number in green, and the path that is followed in yellow.

enter image description here

enter image description here

In the last example we look for 207, which isn’t in the matrix:

enter image description here

This is just the algorithm. The coding is left for you as an exercise 🙂

EDIT: When starting on the bottom row, a binary search might give a better starting point. For the rest of the algorithm it probably doesn’t matter.

Leave a Comment