English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

The input is an N by N matrix of numbers that is already in memory. Each individual row is increasing from left to right. Each individual column is increasing form top to bottom. Give an O(N) worst-case algorithm that decides if a number X is in the matrix.

2006-10-26 21:00:34 · 2 answers · asked by y69627 4 in Science & Mathematics Mathematics

2 answers

If you mean that the increment is by 1 between successive rows and columns, call the first entry in the upper left hand corner k. Now the last number (call it m) in the lower right-hand entry is k+2(N-1). All you have to do is compute m and check k ≤ X ≤ m and you're done.

If you mean that the numbers are increasing by one between successive columns and the next row begins with a value that is N greater that the previous row (also called 'lexigraphic order' for the obvious reason) it becomes m = k+(N²-1) and you do the same thing.


Doug

2006-10-26 21:18:53 · answer #1 · answered by doug_donaghue 7 · 0 0

Let it be A[i,j]
The psedo code logic
let us check for num

for ( i = 1 to N by 1)
if(A[i,1] <= num /* if it is more we need not consider
for k = 1 to N by 1
if(A[i,k] > num go to outer loop
if A[i , K] = num exit found
endfor
else exitloop not found
endif

2006-10-27 04:44:52 · answer #2 · answered by Mein Hoon Na 7 · 0 0

fedest.com, questions and answers