二分查找递归非递归

前言:二分查找是针对于一组有序元素的查找算法,时间复杂度了O(logn)

直接上代码

public class BinarySearch {
    public static void main(String[] args) {
        int[] data = {1,4,6,7,9,12,16,78,98};
        BinarySearch b = new BinarySearch();
        int result = b.binarySearch(data, 1);
        System.out.println(result);
    }

    //iterative
    public int binarySearch(int[] data, int target) {//数组有序用二分查找,时间复杂度O(logn)
        if (data == null || data.length == 0) return -1;//非法输入返回-1

        int low = 0;
        int high = data.length - 1;

        int mid;

        while (low <= high) {//有等于的情况即最后一次二分查找
            //mid = (low + high) / 2;//在循环里面取中间值
            mid = low + (high - low) >> 1;//用移位操作加快速度,同时考虑low + high溢出
            if (target < data[mid]) {
                high = mid - 1;
            }
            else if (target > data[mid]) {
                low = mid + 1;
            }
            else {
                return mid;
            }
        }

        return -1;//找不到返回-1
    }

    //recursive
    public int binarySearch2(int[] data, int low, int high, int target) {//递归法需要加low和high参数
        if (data == null || data.length == 0) return -1;

        if (low <= high) {
            int mid = (low + high) / 2;

            if (target < data[mid]) {
                return binarySearch2(data, low, mid - 1, target);//要return
            }
            else if (target > data[mid]) {
                return binarySearch2(data, mid + 1, high, target);
            }
            else {
                return mid;
            }
        }
        else {
            return -1;
        }

    }
}

你可能感兴趣的:(数据结构)