![在这里插入图片描述](https://img-blog.csdnimg.cn/20210128160743159.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Njg5NzE3Nw==,size_16,color_FFFFFF,t_70)
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
long[][] array = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15}
};
int rows = 3;
int columns = 5;
for (long target = 0; target <= 16; target++) {
int[] index = Search.search(array, rows, columns, target);
System.out.printf("查找 %d 的结果是: %s\n", target, Arrays.toString(index));
}
}
}
public class Search {
public static int[] search(long[][] array, int rows, int columns, long target) {
Range range = new Range(array, rows, columns);
while (range.size() > 0) {
long middleValue = range.getMiddleValue();
if (target == middleValue) {
return range.getMiddleIndex();
} else if (target < middleValue) {
range.discardRightPart();
} else {
range.discardLeftPart();
}
}
return new int[] { -1, -1 };
}
}
public class Range {
private final long[][] array;
private final int columns;
private int lowRow;
private int lowColumn;
private int highRow;
private int highColumn;
public Range(long[][] array, int rows, int columns) {
this.array = array;
this.columns = columns;
this.lowRow = 0;
this.lowColumn = 0;
this.highRow = rows - 1;
this.highColumn = columns - 1;
}
public int size() {
return (columns - lowColumn) + ((highRow - lowRow - 1) * columns) + (highColumn + 1);
}
public long getMiddleValue() {
int[] index = getMiddleIndex();
int row = index[0];
int column = index[1];
return array[row][column];
}
public int[] getMiddleIndex() {
int halfSize = size() / 2;
int middleRow = lowRow;
int middleColumn = lowColumn;
middleColumn += halfSize;
while (middleColumn >= columns) {
middleRow++;
middleColumn -= columns;
}
return new int[] { middleRow, middleColumn };
}
public void discardRightPart() {
int[] index = getMiddleIndex();
int row = index[0];
int column = index[1];
highRow = row;
highColumn = column - 1;
if (highColumn < 0) {
highRow--;
highColumn = columns - 1;
}
}
public void discardLeftPart() {
int[] index = getMiddleIndex();
int row = index[0];
int column = index[1];
lowRow = row;
lowColumn = column + 1;
if (lowColumn >= columns) {
lowRow++;
lowColumn = 0;
}
}
}