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

二分查找法的递归与非递归

程序员文章站 2024-03-23 23:07:28
...

二分查找法的两种实现方式:

    class BinarySearch{
        private int[] array;
        public BinarySearch(int[] array){
            this.array=array;
        }
        //递归方式
        public int searchRecursion(int target){
            if(array!=null){
                return searchRecursion(target,0,array.length-1);
            }
            return -1;
        }
        public int searchRecursion(int target,int start,int end){
            if(start>end){
                return -1;
            }
            int mid=start+(end-start)/2;
            if(array[mid]==target){
                return mid;
            }else if(target<array[mid]){
                return searchRecursion(target,start,mid-1);
            }else{
                return searchRecursion(target,mid+1,end);
            }
        }
        //非递归
        public int search(int target){
            if(array==null){
                return -1;
            }
            int start=0;
            int end=array.length-1;
            while(start<=end){
                int mid=start+(end-start)/2;
                if(array[mid]==target){
                    return mid;
                }else if(target<array[mid]){
                    end=mid-1;
                }else{
                    start=mid+1;
                }
            }
            return -1;
        }
    }