二分法

二分法

二分法能够在有序数组中快速找到某一个数的算法,比循环迭代快很多
说明
1.长度为100的数组【1,2,3,4,5,6,7,8,...,99】 如果想要找到66这个数,我们循环查找需要 寻找66次
2. 用二分法我们第一次数组长度减1 99/2=49 49 49<66 左边0~49数组全部不要 第二次取右边数组(50+99)/2=79 79>66 第三次取(50+79)/2=64 一直二分下去找到66
demo

package com.day03;

/**
 * 
 * 二分法 在一个有序数组中找到某一个数
 * 
 * @author wanli 2020年12月25日
 */
public class Bisection {

    static int[] array = new int[100];

    static {
        for (int i = 0; i < array.length; i++) {
            array[i] = i;
        }
    }

    public static void main(String[] args) {
        boolean flag = biseetionArray(array, 1);
        if (flag) {
            System.out.println("找到了");
        } else {
            System.out.println("没找到");
        }
    }

    public static boolean biseetionArray(int[] array, int num) {

        int a = 0;
        int b = array.length - 1;
        while (a <= b) {
            int c = (a + b) / 2;
            if (c == num) {
                return true;
            } else if (c < num) {
                // c<num 取二分右边得数组
                // example num=60 二分50 取数组下标 51~100-1
                a = c + 1;
            } else {
                // c>num 取二分左边得数组
                // example num=30 二分50 取数组下标 0~29
                b = c - 1;
            }
        }
        return false;
    }
}

效果如图

二分法 题目1

在一个有序数组找到1个数最左边的数 最左边这个数大于改数
说明
1.数组array [1,2,4,4,5,6,7,8,8,8] 找到8最左边的数, 就是找到数组下标7这个数为8
demo

public class BeisectionLeft {
    static int[] array = {1, 2, 4, 4, 5, 6, 7, 8, 8, 8};

    public static int findLeftNum(int[] array, int num) {
        int a = 0;
        int b = array.length - 1;
        // 给定初始位置下标
        int inx = -1;
        while (a <= b) {
            int c = (a + b) / 2;
            if (array[c] >= num) {
                inx = c;
                b = c - 1;
            } else {
                a = c + 1;
            }
        }
        return inx;
    }

    public static void main(String[] args) {
        int findLeftNum = findLeftNum(array, 8);
        System.out.println("数组为" + findLeftNum + "该数为" + array[findLeftNum]);

    }
}

posted @ 2020-12-25 22:06  IT-only-wan  阅读(38)  评论(0)    收藏  举报