二分查找算法

时间:2021-02-16 04:08:12
/*
 * 二分查找算法也称为折半搜索、二分搜索,是一种在有序数组中查找某一特定元素的搜索算法。
 * 请注意这种算法是建立在有序数组基础上的。
 * */
public class BinarySearch {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18};
        int fromIndex=0;
        int toIndex = a.length-1;
        int key=5;
        System.out.println(binarySearch0(a,fromIndex,toIndex,key));
    }
    
    private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) {
        int low = fromIndex;
        int high = toIndex-1;
        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];
            if (midVal < key)
            low = mid + 1;
            else if (midVal > key)
            high = mid - 1;
            else
            return mid; // key found
        }
        return -(low + 1);  // key not found.
        } 
}