I wonder, can binary search be applied on a 2D array?
I solved it in a simple way in O(m + n)
time complexity, where m = no. of rows and n = no. of columns.
The algorithm is simple: I started from top right corner (we can also start from bottom left corner) and move left if current element is greater than the value to be searched and bottom if current element is smaller than the value to be searched.
The java code is like:
public static int[] linearSearch(int[][] a, int value) {
int i = 0, j = a[0].length - 1; // start from top right corner
while (i < a.length && j >= 0) {
if (a[i][j] == value) {
return new int[]{i, j};
} else if (a[i][j] > value) {
j--; // move left
} else {
i++; // move down
}
}
// element not found
return new int[]{-1, -1};
}
Gist
You can further reduce the time complexity by using a method called Improved Binary Partition.