此处设为各行各列递增的数组,示例如下:
该类数组查找的要点是找到起点,若如上所示是各行各列递增,那么可选取右上角顶点为起点,效果为:当搜索值(称为num)不等于该顶点值(称为point)时,搜索范围可一致减小;
所谓一致减小,就是范围减小后符合同一规律:
在该例中,由于递增:
若 num〉point,可确定该点所在行均不符合要求,可将该point下移一行;
搜索范围简化为:
若 num〈point,可确定该点所在列均不符合要求,可将该point左移一列;
搜索范围简化为:
若数列为递减:
JAVA代码如下:
public class Main {
private int[][] array = new int[][] { { 1, 2, 8, 9 }, { 2, 4, 9, 12 },
{ 4, 7, 10, 13 }, { 6, 8, 11, 15 } };
public boolean search(int N, int M, int num) {
int startRow = 0;
int startCol = M - 1;
while (startRow < N && startCol >= 0) {
if (array[startRow][startCol] < num)
startRow++;
else if (array[startRow][startCol] > num)
startCol--;
else
return true;
}
return false;
}
public static void main(String[] args) {
Main m = new Main();
System.out.println(m.search(4, 4,5));
}
}