public class BinarySearch { /* * 循環實現二分查找算法arr 已排好序的數組x 須要查找的數-1 沒法查到數據 */ public static int binarySearch(int[] arr, int x) { int low = 0; int high = arr.length-1; while(low <= high) { int middle = (low + high)/2; if(x == arr[middle]) { return middle; }else if(x <arr[middle]) { high = middle - 1; }else { low = middle + 1; } } return -1; } //遞歸實現二分查找 public static int binarySearch(int[] dataset,int data,int beginIndex,int endIndex){ int midIndex = (beginIndex+endIndex)/2; if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex){ return -1; } if(data <dataset[midIndex]){ return binarySearch(dataset,data,beginIndex,midIndex-1); }else if(data>dataset[midIndex]){ return binarySearch(dataset,data,midIndex+1,endIndex); }else { return midIndex; } } public static void main(String[] args) { int[] arr = { 6, 12, 33, 87, 90, 97, 108, 561 }; System.out.println("循環查找:" + (binarySearch(arr, 87) + 1)); System.out.println("遞歸查找"+binarySearch(arr,3,87,arr.length-1)); } }
對於含有n個數據元素的查找表,查找成功的平均查找長度爲:ASL=∑PiCi (i=1,2,3,…,n)。其中:Pi 爲查找表中第i個數據元素的機率,Ci爲找到第i個數據元素時已經比較過的次數,∑Pi=1。html
返回目錄java
ASL=1/n * ∑Ci = 1/11 * (1 + 2 * 2 + 4 * 3 + 4 * 4) = 33/11 = 3git
返回目錄算法
返回目錄數據結構