1. 程式人生 > 資料庫 >Python modbus rtu slave+mysql+隨機數生產模擬資料

Python modbus rtu slave+mysql+隨機數生產模擬資料

二分法

二分法能夠在有序陣列中快速找到某一個數的演算法,比迴圈迭代快很多
說明
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]);

    }
}