二分尋找法

來源:互聯網
上載者:User

標籤:遞迴   尋找演算法   blog   binary   一個   sys   比較   index   stat   

 

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

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

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

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

5.代碼:

 1 package other; 2  3 public class BinarySearch { 4     /* 5      * 迴圈實現二分尋找演算法arr 已排好序的數組x 需要尋找的數-1 無法查到資料 6      */ 7     public static int binarySearch(int[] arr, int x) { 8         int low = 0;    9         int high = arr.length-1;   10         while(low <= high) {   11             int middle = (low + high)/2;   12             if(x == arr[middle]) {   13                 return middle;   14             }else if(x <arr[middle]) {   15                 high = middle - 1;   16             }else {   17                 low = middle + 1;   18             }  19         }  20         return -1;  21     }22     //遞迴實現二分尋找23     public static int binarySearch(int[] dataset,int data,int beginIndex,int endIndex){    24            int midIndex = (beginIndex+endIndex)/2;    25            if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex){  26                return -1;    27            }  28            if(data <dataset[midIndex]){    29                return binarySearch(dataset,data,beginIndex,midIndex-1);    30            }else if(data>dataset[midIndex]){    31                return binarySearch(dataset,data,midIndex+1,endIndex);    32            }else {    33                return midIndex;    34            }    35        }   36 37     public static void main(String[] args) {38         int[] arr = { 6, 12, 33, 87, 90, 97, 108, 561 };39         System.out.println("迴圈尋找:" + (binarySearch(arr, 87) + 1));40         System.out.println("遞迴尋找"+binarySearch(arr,3,87,arr.length-1));41     }42 }

 

二分尋找法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.