I wonder, can binary search be applied on a 2D array?
You can transform 2D array into 1D array and do the binary search here. Complexity is O(log(m * n))
for mxn
array.
Binary Search works in the divide and conquer way,
int r = arr.length; // ROW Count
int c = arr[0].length; // Column Count
int start = 0; // Initialize with the 0
int end = r*c-1; // Last Index
We will keep iterating the while loop, each time we updating the start and end index as per requirements..
while(start <= end){
int mid = (start+end)/2;
int midX = mid/c;
int midY = mid%c;
If the current value is equals to the search element then we just have to print and return it.
if(arr[midX][midY] == searchElement){
return true;
}
If the current value is smaller then the search element then we just have to update the mid value by mid = mid + 1
if(arr[midX][midY] < searchElement){
start = mid+1;
}
If the current value is grater than the search element then we just have to update the mid value by mid = mid - 1
else{
end = mid-1;
}