Start at the last element of the first row(top-right corner).
Compare it with the key
. We have 3 cases:
If they are equal we are done.
If key
is greater than that element
then it means key
cannot be present
in that row so move the search
to the element below it.
If key
is less than that element then
it means key
could be present in that
row towards left and cannot be present in the column further down, so move the search
to the element left of it.
Keep doing it till you find the element or you cannot further move(key does not exist).
Pseudo code:
Let R be number of rows
Let C be number of columns
Let i = 0
Let j = C-1
found = false
while( i>=0 && i=0 && j key )
j--
else if( matrix[i][j] < key )
i++
end-while