二分查找算法的两种实现

前提条件必须元素有序 ,推荐第一种

package binary;

public class Test {
    public static void main(String[] args) {

        // int[] i = new int[]{1,4,6,8,9,11,33,44,55};
        int[] i = { 3, 6, 8, 9, 11, 55, 66 };
        int index = BinarySearch(i, 11);
        System.out.println(index);
    }
    public static int BinarySearch(int[] array, int key) {
        int min = 0;
        int max = array.length - 1;
        while (min <= max) {
            int mid = (min + max) >> 1;
            if (key > array[mid])
                min = mid + 1;
            else if (key < array[mid])
                max = mid - 1;
            else
                return mid;//mid为所查元素下标
        }
        return min;//如果要查询的元素在数组中都不存在 返回要查询的的元素在数组中的位置(介于两个数下标中间)

    }
    public static int BinarySearch2(int[] array , int key){
        int min = 0;
        int max = array.length - 1;
        int mid = (min + max) >> 1;
        while( array[mid] != key){
            if(key > array[mid])
                min = mid + 1;
            else if( key < array[mid])
                max = mid - 1;
            if(min > max)
                return -1;
             mid = (min + max) >> 1;
        }
        return mid;
    }
}

你可能感兴趣的:(数据结构与算法)