Java实现二分查找

一、代码

package algorithm;

public class BinarySearch {

    public static int binarySearch(int[] arr, int key) {
        if (null == arr || arr.length <= 0) {
            return -1;
        }

        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int middle = (left + right) / 2;
            if (key == arr[middle]) {
                return middle;
            }
            if (key < arr[middle]) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }

        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
        System.out.println(binarySearch(arr, 18));
    }

}

二、运行结果

posted @ 2019-04-14 11:01  wangzaiplus  阅读(...)  评论(... 编辑 收藏