[Java]
/**
* Two-Dimensional binary search for Recursive grouping algorithm Learning
* @ Author Sking
Problem description:
A two-dimensional array T [m] [n] exists. each row of elements increments from left to right,
Each column increments from top to bottom. Now you need to find element X (which must be in two-dimensional
In the array), the time complexity must not exceed m + n.
*/
Recursive grouping of package;
Public class BinarySearchInArray {
/**
* Implementation of two-dimensional Binary Search
* @ Param array the two-dimensional array to be searched
* @ Param value the element to be searched
* @ Param m1 horizontal coordinates in the upper left corner of the array
* @ Param n1 the vertical coordinates in the upper left corner of the array
* @ Param m2 horizontal coordinates in the lower right corner of the array
* @ Param n2 ordinate the bottom right corner of the array
* @ Return the index of the position of the element to be searched in a two-dimensional array, which exists in an array with a length of 2
* If not found, null is returned.
*/
Int [] binarySearchInArray (int [] [] array, int value, int m1, int n1, int m2,
Int n2 ){
// (BeginX, beginY) indicates the coordinates in the upper left corner of the array
Int beginX = m1, beginY = n1;
// (EndX, endY) indicates the coordinates at the bottom right corner of the array
Int endX = m2, endY = n2;
Int [] leftResult = new int [2]; // search result in the lower left corner of recursive search
Int [] rightResult = new int [2]; // the search result in the upper-right corner obtained by recursive search
Int I = (m1 + m2)/2, j = (n1 + n2)/2; // not a diagonal Array
If (value <array [m1] [n1] | value> array [m2] [n2])
Return null;
If (value = array [m1] [n1])
Return new int [] {m1, n1 };
If (value = array [m2] [n2])
Return new int [] {m2, n2 };
// Binary search in the diagonal direction of the sub-matrix to determine the Recursive Sub-Matrix
While (I! = M1 | j! = N1) & (I! = M2 | j! = N2 )){
If (value = array [I] [j])
Return new int [] {I, j };
Else if (value <array [I] [j]) {
M2 = I;
N2 = j;
I = (I + m1)/2;
J = (j + n1)/2;
} Else {
M1 = I;
N1 = j;
I = (I + m2)/2;
J = (j + n2)/2;
}
} // If it is found, return. Otherwise, perform recursive search on the matrix in the lower left corner and upper right corner.
If (I <endX) // recursive search in the upper right corner
LeftResult = binarySearchInArray (array, value, I + 1, beginY, endX, j );
If (j <endY) // recursive search in the lower left corner
RightResult = binarySearchInArray (array, value, beginX, j + 1, I, endY );
If (leftResult! = Null)
Return leftResult;
If (rightResult! = Null)
Return rightResult;
Return null;
}
}