I wonder, can binary search be applied on a 2D array?
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:
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:
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:
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).