Java-数据结构与算法-二分查找法

时间:2021-03-02 13:21:05

1.二分查找法思路:不断缩小范围,直到low <= high

2.代码:

 package Test;

 import java.util.Arrays;

 public class BinarySearch {

     public static void main(String[] args) {
int [] a = {1,5,7,9,11,12,16,20};
int target = 16;
//System.out.println(Arrays.binarySearch(a, target));
System.out.println(binarySearch(a, target));
} public static int binarySearch(int [] a, int target){
int low = 0;
int high = a.length - 1; while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid]; if (midVal < target)
low = mid + 1;
else if (midVal > target)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
}

3.结果:6