public class Search {
public static int binary(int[] number, int destination) {
int start = 0;
int end = number.length - 1;
while (start <= end) {
int middle = (start + end) / 2;
if (number[middle] == destination) {
return middle; // found
} else if (number[middle] < destination) {
start = middle + 1;
} else if (number[middle] > destination) {
end = middle - 1;
}
}
return -1; // not found
}
public static void main(String[] args) {
int[] number = {1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
int find = Search.binary(number, 42);
System.out.println(find >= 0 ? "找到数值于索引 " + find : "找不到数值");
}
}
网友评论