二分尋找演算法(JAVA)

來源:互聯網
上載者:User

標籤:迴圈   while   style   二分尋找   arch   ini   方法   二分   int   

1.二分尋找又稱折半尋找,它是一種效率較高的尋找方法。

2.二分尋找要求:(1)必須採用順序儲存結構 (2).必須按關鍵字大小有序排列

3.原理:將數組分為三部分,依次是中值(所謂的中值就是數組中間位置的那個值)前,中值,中值後;將要尋找的值和數組的中值進行比較,若小於中值 則在中值前 面找,若大於中值則在中值後面找,等於中值時直接返回。然後依次是一個遞迴過程,將前半部分或者後半部分繼續分解為三部分。

4.實現:二分尋找的實現用遞迴和迴圈兩種方式

public class BinarySearch {    /**     * 迴圈實現二分尋找演算法     *     * @param arr  已排好序的數組     * @param data 需要尋找的數     * @return 需要尋找的數在數組中的索引,無法查到資料則返回-1     */    public static int binarySearch(int[] arr, int data) {        int beginIndex = 0;        int endIndex = arr.length - 1;        while ((beginIndex <= endIndex) && (beginIndex <= arr.length - 1) && (endIndex <= arr.length - 1)) {            int midIndex = (beginIndex + endIndex) / 2;            if (data == arr[midIndex]) {                return midIndex;            } else if (data < arr[midIndex]) {                endIndex = midIndex - 1;            } else {                beginIndex = midIndex + 1;            }        }        return -1;    }    /**     * 遞迴實現二分尋找     *     * @param arr        已排好序的數組     * @param data       需要尋找的數     * @param beginIndex 開始索引     * @param endIndex   結束索引     * @return 需要尋找的數在數組中的索引,無法查到資料則返回-1     */    public static int binarySearch(int[] arr, int data, int beginIndex, int endIndex) {        int midIndex = (beginIndex + endIndex) / 2;        if (data < arr[beginIndex] || data > arr[endIndex] || beginIndex > endIndex) {            return -1;        }        if (data < arr[midIndex]) {            return binarySearch(arr, data, beginIndex, midIndex - 1);        } else if (data > arr[midIndex]) {            return binarySearch(arr, data, midIndex + 1, endIndex);        } else {            return midIndex;        }    }    public static void main(String[] args) {        int[] arr = {6, 12, 33, 87, 90, 97, 108, 561};        //3        System.out.println("迴圈尋找:" + binarySearch(arr, 87));        //3        System.out.println("遞迴尋找" + binarySearch(arr, 87, 0, arr.length - 1));    }}

 

二分尋找演算法(JAVA)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.