/**
- 二分查找
- 时间复杂度:O(n)
*/
public class BinarySearch {
public static void main(String[] args) {
int [] arr = {1,3,5,7,9};
int a = binary_search(arr,10);
System.out.println("该元素的下标为:"+a);
}
public static int binary_search(int[] arr,int item){
int low = 0;
int high = arr.length - 1;
while (low <= high){
int mid = (low + high)/2;
int guess = arr[mid];
if (guess == item){
return mid;
}
if (guess > item){
high = mid -1;
}else {
low = mid + 1;
}
}
return -1;
}
}