/**
* 二分查找:
* 时间复杂度:O(log n)
*/
public class BinarySearch {
// 存在返回查找元素的下表,不存在返回-1
public static int binarySearch(int[] sortedArr, int num) {
int L = 0;
int R = sortedArr.length-1;
while (L <= R) {
int mid = L + (R-L)/2;
if (sortedArr[mid] > num) {
R = mid-1;
} else if (sortedArr[mid] < num) {
L = mid+1;
} else {
return mid;
}
}
return -1;
}
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int index = binarySearch(a, 9);
if(index != -1)
System.out.printf("a[%d] = %d", index, a[index]);
else
System.out.println("查询无结果");
}
}
二分查找的思想很重要