欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java给定一个有序整型数组, 实现二分查找

程序员文章站 2024-03-17 14:43:04
...
public static int findKey(int[] array,int key) {
        int left = 0;
        int right = array.length-1;
        int mid = (left + right)/2;
        while(left <= right) {
            mid = (left + right)/2;
            if (key > array[mid]) {
                left = mid + 1;
            }
            else if(key < array[mid]) {
                right = mid - 1;
            }
            else {
                return mid;
            }
        }
        return -1;
    }
    public static void main(String[] args) {
        int [] arr = new int[] {1,2,3,4,5,6};
        int key = 5;
        int ret = findKey(arr,key);
        System.out.println(ret);
        //给定一个有序整型数组, 实现二分查找
    }
}