I thought about this problem last year... So, I'd choosed this approach:
Consider your 2D-array represents points in a plane. For example, your element A[i][j] represents a point with x = i and y = j. To use binary search on the plane I sort all points using this condition:
point p1 < p2 if and only if:
- (x-coordinate of p1) < (x-coordinate of p2)
- (x-coordinate of p1) = (x-coordinate of p2) and (y-coordinate of p1) < (y-coordinate of p2)
Othwerwise p1 >= p2.
Now, if we look to our 2D-array, elements in 2nd row should be greater than elements in 1st row. In same row elements sorted as usual (according to their column number).
In another words:
- A[i][j] > A[k][j] if and only if (i>k). (in different rows and in same column)
- A[i][j] > A[i][k] if and only if (j>k). (in the same row and different columns)
Consider your array has N rows and M columns. Now you should (temporarly) transform your 2D array to 1D array using this formula (T - temporary array):
for i:=0 to N-1 do
for j:=0 to M-1 do
T[i*N + j]:= A[i][j];
Now you have 1D array. Sort it in usual way. And now you can search in it using simple binary search algorithm.
Or you can transform your sorted array back to 2D array using this formula:
for i:=0 to N*M-1 do
A[i div N][i - (i div N)*N]:= T[i];
And use two binary searches:
One search by x-coordinate (by rows in our meaning), another one by y-coordinate (by columns in our meaning) for elements in same row.
In another words, when you calculate mid = mid + (max - min) div 2
, you can compare element A[mid][0] with your key-element(in your code it has x name) and when you find row with your element, you can call another binary search in this row (binary search in A[mid]).
Complexity for both methods:
- for simple binary search in trasformed array: log(N*M)
- for two binary searches in 2D array: log(N) for outer search (in rows) + log(M) for inner search (in columns).
Using the properties of logarithm function we can simplify last expression: log(N) + log(M) = log(N*M).
So, we proved, that both methods has same complexity and doesn't matter, which one to use.
But, if it's not hard to you, I suggest you simply transform your array to 1-D and use simple binary search (it's very simple and easy to debug and check).
min = 1
andmax = 1
. Thenmid := min + (max - min) div 2
results inmid = 0
(assuming integer arithmetic). Then who knows whatA[mid]
equates to (givenA
is indexed as: 1..N). – Claypanmid := min + (max - min) DIV 2
results in 1, which is just fine. – Claypan