[Java]
/**
* Recursive divide-and-conquer algorithm learning two-dimensional binary search
* @author sking
Problem Description:
There is a two-dimensional array t[m][n], and each line element increments from left to right,
Each column element is incremented from top to bottom, and now you need to find the element x (must be in two-dimensional
The position of the array in the array requires a time complexity of no more than m+n.
*/
Package recursive divide and conquer;
public class Binarysearchinarray {
/**
* Implementation of two-dimensional binary search
* @param array of two-dimensional arrays to find
* @param value to find the element
* @param the upper left corner of the M1 array
* @param the upper-left ordinate of the N1 array
* @param m2 array right bottom corner horizontal
* @param n2 array right bottom corner ordinate
* @return The position index of the element to be found in a two-dimensional array, in an array of length 2
* Returns null if not found.
*/
Int[] Binarysearchinarray (int[][] array, int value, int m1, int n1, int m2,
int N2) {
(Beginx,beginy) represents the upper-left coordinate of the array
int BeginX = m1, BeginY = N1;
(Endx,endy) indicates the coordinates of the lower-right corner of the array
int endx = m2, EndY = n2;
int[] Leftresult = new int[2];//recursive find bottom left search results
int[] Rightresult = new int[2];//recursive find top right search results
int i = (m1 + m2)/2, J = (n1 + n2)/2;//not 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};
Sub-matrix binary search in diagonal direction, determine 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;
}
}//returns if found, or recursively finds the lower-left and upper-right matrices
if (I < ENDX)//upper right corner recursive lookup
Leftresult = Binarysearchinarray (array, value, I + 1, beginy, endx,j);
if (J < EndY)//left lower corner recursive lookup
Rightresult = Binarysearchinarray (array, value, BeginX, J + 1, I,endy);
if (Leftresult! = null)
return leftresult;
if (Rightresult! = null)
return rightresult;
return null;
}
}
Two-dimensional array binary lookup (Java version) of recursive divide-and-conquer algorithm