每天一道算法题(二分查找)

/**
 * 二分查找
 */
public class HalfSearch {

    public static void main(String[] args) {
        int[] a = new int[]{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
        int searchNum = 18;
        System.out.println("index=" + (bsearch(a, 11, searchNum) + 1));
    }

    public static int bsearch(int[] a, int n, int val) {
        return bsearchInternally(a, 0, n - 1, val);
    }

    private static int bsearchInternally(int[] a, int low, int high, int value) {
        if (low > high) return -1;
        int mid= (low+high)/2;
        if (a[mid] == value) {
            return mid;
        }
        else if (a[mid] < value) {
            return bsearchInternally(a, mid+1, high, value);
        } else {
            return bsearchInternally(a, low, mid-1, value); }
    }

}
posted @ 2021-03-30 13:17  梦见舟  阅读(51)  评论(0编辑  收藏  举报