標籤:遞迴 尋找演算法 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 }
二分尋找法