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 { // new int[] { 0, 3 } 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 }; // return null; }}
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; // middleColumn 還不是一個合法下標 while (middleColumn >= columns) { middleRow++; middleColumn -= columns; } return new int[] { middleRow, middleColumn }; } public void discardRightPart() { // 讓 high 往左走,不包括 middle 位置 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() { // 讓 low 往右做,不包括 middle 位置 int[] index = getMiddleIndex(); int row = index[0]; int column = index[1]; lowRow = row; lowColumn = column + 1; // 不要中間位置 if (lowColumn >= columns) { lowRow++; lowColumn = 0; } }}