二分查找法的递归和非递归的实现

    //二分查找法非递归实现,在一个有序的数组中查找e元素的位置,找不到返回-1
    public static int binarySearch(int[] data,int e){
        int l = 0;
        int r = data.length - 1;

        while (l <= r){
            int mid = (l + r) / 2;

            if(e > data[mid]){
                l = mid + 1;
            }else if(e < data[mid]){
                r = mid - 1;
            }else {
                return mid;
            }

        }
        return -1;
    }
  //二分查找法的递归实现
    public static int binarySearchRecursion(int[] data,int l,int r,int e){
        int mid = (l + r) / 2;
        if(e > data[mid] ){
            return binarySearchRecursion(data,mid + 1,r,e);
        }else if(e < data[mid] ){
            return binarySearchRecursion(data,l,mid - 1,e);
        }else {
            return mid;
        }
    }

你可能感兴趣的:(二分查找法的递归和非递归的实现)