二分查找算法及时间复杂度
程序员文章站
2024-03-20 10:07:52
...
public class Test{
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6,7,8,9,10};
System.out.println(binarySearch(arr, 11));
}
private static int binarySearch(int[] arr, int key){
int low = 0;
int high = arr.length-1;
int middle;
while(low <= high){
middle = (low+high)/2;
if(arr[middle] > key){
high = middle-1;
}else if(arr[middle] < key){
low = middle+1;
}else{
return middle;
}
}
return -1;
}
}
时间复杂度:O(log2n)
上一篇: 最长公共子序列问题
下一篇: Java二分查找代码实现