目标:熟练运用 Java所学知识
本文内容:使用java语言实现:给定一个有序整型数组, 实现二分查找
public class practice {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
System.out.println(binarySearch(arr, 4));
}
private static int binarySearch(int[] arr, int toFind) {
int left = 0;//左端点下标
int right = arr.length - 1;//右端点下标
while (left <= right) {
int mid = (left + right) / 2;
if (toFind < arr[mid]) {
//去左区间找
right = mid - 1;
} else if (toFind > arr[mid]) {
//去右区间找
left = mid + 1;
} else {
//相等,说明找到了
return mid;
}
}
//循环结束,说明没找到
return -1;
}
}
3