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

Java实现二分查找递归和非递归

程序员文章站 2022-03-14 20:41:09
...

Java实现二分查找递归和非递归

public class Demo {

    public static void main(String[] args) {
        int[] arr={-1,0,3,5,9,12};//查找的数组
        int searchNum=13;//查找的目标数
        Arrays.sort(arr);

        int resultOne=binarySearchOne(arr,searchNum,0,arr.length-1);
        System.out.println(resultOne);

        int resultTwo=binarySearchTwo(arr,searchNum);
        System.out.println(resultTwo);
    }

    /**
     * 递归实现
     * @param arr
     * @param searchNum
     * @param start
     * @param end
     * @return
     */
    public static int binarySearchOne(int[] arr,int searchNum,int start,int end){
        if(start>end)
            return -1;
        int middle=(start+end)/2;
        if(searchNum<arr[middle])
            return binarySearchOne(arr,searchNum,start,middle-1);
        else if(searchNum>arr[middle])
            return binarySearchOne(arr,searchNum,middle+1,end);
        else
            return middle;
    }

    /**
     * 非递归实现
     * @param arr
     * @param searchNum
     * @return
     */
    private static int binarySearchTwo(int[] arr, int searchNum) {
        int start=0;
        int end=arr.length-1;
        while(start<=end){
            int middle=(start+end)/2;
            if(searchNum<arr[middle])
                end=middle-1;
            else if(searchNum>arr[middle])
                start=middle+1;
            else
                return middle;
        }
        return -1;
    }
}