java二分查找(BinarySearch)
程序实现
public class BinarySearch {
public static void main(String[] args) {
int[] sum = {1, 5, 6, 7, 9, 15, 16, 18, 56, 59, 64, 68, 98};
Scanner sc=new Scanner(System.in);
int target = sc.nextInt();
int id = binarySearch(sum, target);
System.out.println(id);
}
public static int binarySearch(int[] sum, int target) {
int left = 0;
int right = sum.length - 1;
while (left <= right) {
int temp = (left + right) >>> 1;
if (target == sum[temp]) {
return temp;
} else if (target > sum[temp]) {
left = temp + 1;
} else {
right = temp - 1;
}
}
return -1;
}
}