算法学习——二分查找(折半查找)

算法学习——二分查找

注意点

1. 二分查找的前提是有序的数组
2. 建议使用[start,end)的区间寻找,符合规范
3. 使用的是递归法

递归的人口

private static int find(int[] temp, int x) {
		//如果要查找的数x比数组的最后一个数要大,则找不到数值,返回-1
        if (x > temp[temp.length - 1]) {
            return -1;
        }
        return find(temp, 0, temp.length, x);//进入递归
}

递归的出口

private static int find(int[] temp, int start, int end, int x) {
        if (end - start == 1) {
            return -1;//出口
        }
        int mid = (start + end) / 2;
        if (x < temp[mid]) {
            return find(temp, start, mid, x);
        } else {
            if (x == temp[mid]) {
                return mid;//出口
            }
            return find(temp, mid, end, x);
        }
}

按照过程跑一遍就能够对二分查找有个深刻的理解,我觉得书上的有个while循环,要想半天才能想通

二分查找,返回数组中的查找到该数的下标值

public static void main(String[] args) {
        int[] data = {5, 6, 9, 15, 19, 53, 56};
        System.out.println(find(data,15));
    }

    private static int find(int[] temp, int x) {
        if (x > temp[temp.length - 1]) {
            return -1;
        }
        return find(temp, 0, temp.length, x);
    }

    private static int find(int[] temp, int start, int end, int x) {
        if (end - start == 1) {
            return -1;
        }
        int mid = (start + end) / 2;
        if (x < temp[mid]) {
            return find(temp, start, mid, x);
        } else {
            if (x == temp[mid]) {
                return mid;
            }
            return find(temp, mid, end, x);
        }
    }

二分查找,比要找的数大一点的数的下标(修改一下出口)

public static void main(String[] args) {
        int[] data = {5, 6, 9,9, 15, 19, 53, 56};
        System.out.println(find(data,14));
    }

    private static int find(int[] temp, int x) {
        if (x > temp[temp.length - 1]) {
            return -1;
        }
        return find(temp, 0, temp.length, x);
    }

    private static int find(int[] temp, int start, int end, int x) {
        if (end - start == 1) {
            return end;//后一个肯定比前一个大,返回后一个,start已经比较过了,temp[start]比x要小
        }
        int mid = (start + end) / 2;
        if (x < temp[mid]) {
            return find(temp, start, mid, x);
        } else {
            if (x == temp[mid]) {
                return mid+1;//找到了当前的数,之后的那个数肯定比当前的数大点
            }
            return find(temp, mid, end, x);
        }
    }
posted @ 2019-03-08 20:41  Stars-one  阅读(528)  评论(0编辑  收藏  举报