二分查找的两种实现方式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jinhuoxingkong/article/details/74926240

第一种是递归查找

第二种是非递归查找

public class testMain {
    public static void main(String args[]){
        int array[] = new int[]{1, 2, 2, 3, 4 ,5, 6 ,7 ,8};
        int res = binarySearch(array, 0, 8, 4);
        int res1 = binarySearch1(array, 0, 8, 4);
        System.out.println("res = "+res);
        System.out.println("res = "+res1);
    }
    //使用递归的方式
    public static int binarySearch(int array[], int left, int right, int target){
        if(left < right){
            int mid = (left + right)/2;
            if(array[mid] == target){
                return mid;
            }
            if(target < array[mid]){
                return binarySearch(array, left, mid-1, target);
            }
            if(target > array[mid]){
                return binarySearch(array, mid+1, right, target);
            }
        }
        return -1;
    }




    //使用普通的方式
    public static int binarySearch1(int array[], int left, int right, int target){
        while(left <= right){
            int mid = (left + right)/2;
            if(array[mid] == target){
                return mid;
            }
            if(target < array[mid]){
                right = mid-1;
            }
            if(target > array[mid]){
                left = mid+1;
            }
        }
        return -1;
    }

}


阅读更多
换一批

没有更多推荐了,返回首页