# 二分查詢的遞迴與非遞迴實現
阿新 • • 發佈:2018-12-14
二分查詢的遞迴與非遞迴實現
二分查詢也稱為折半查詢,首先,假設表中元素是按升序排列,將表中間位置記錄的關鍵字與查詢關鍵字比較,如果兩者相等,則查詢成功;否則利用中間位置記錄將表分成前、後兩個子表,如果中間位置記錄的關鍵字大於查詢關鍵字,則進一步查詢前一子表,否則進一步查詢後一子表。重複以上過程,直到找到滿足條件的記錄,使查詢成功,或直到子表不存在為止,此時查詢不成功。
思想比較簡單,話不多說,直接上程式碼:
/* * 二分查詢,遞迴與非遞迴實現 */ public class binarySearch { public static void main(String[] args) { // TODO Auto-generated method stub int a[] = {11,13,15,22,45,67,88,99,100,140}; int key1 = bsResursion(a, 0, a.length-1, 99); System.out.println(key1); int key2 = bs(a, 45); System.out.println(key2); } public static int bs(int a[],int key) { //非遞迴實現 int low = 0; int hight = a.length - 1; while(low < hight) { int middle = (low + hight) / 2; if(a[middle] == key) { return middle; }else if(a[middle] < key) { low = middle + 1; }else if(a[middle] > key) { hight = middle - 1; } } return -1; } public static int bsResursion(int a[], int low, int hight, int key) { //遞迴實現 if(low > hight) { return -1; } int middle = (low + hight) / 2; if(a[middle] == key) { return middle; }else if(key > a[middle]) { return bsResursion(a, middle+1, hight, key); }else if(key < a[middle]) { return bsResursion(a, low, middle-1, key); } return -1; } }
執行結果: