1. 程式人生 > >二分查詢演算法的 java 實現

二分查詢演算法的 java 實現

遞迴實現:

    public static int binsearch(int[] arr, int num, int begin, int end) {
        int midnum = (begin + end) / 2;
        if (begin >= end) {
            return -1;
        }
        if (num < arr[midnum]) {
            return binsearch(arr, num, begin, midnum - 1);
        } else if (num > arr[midnum]) {
            return binsearch(arr, num, midnum + 1, end);

        } else{
            return midnum;
        }
    }

普通實現:

    public static int binsearch(int arr[], int num) {
        int midnum;
        int begin = 0;
        int end = arr.length - 1;
        while (begin <= end) {
            midnum = (end + begin) / 2 ;
            if (num < arr[midnum]) {
                end = midnum - 1;
            } else if (num > arr[midnum]) {
                begin = midnum + 1;
            } else {
                return midnum;
            }
        }
        return -1;
    }