查詢--二分查詢(Java)
阿新 • • 發佈:2020-06-30
查詢--二分查詢(Java)
部落格說明
文章所涉及的資料來自網際網路整理和個人總結,意在於個人學習和經驗彙總,如有什麼地方侵權,請聯絡本人刪除,謝謝!
介紹
二分查詢也稱折半查詢(Binary Search),它是一種效率較高的查詢方法。但是,折半查詢要求線性表必須採用順序儲存結構,而且表中元素按關鍵字有序排列。
過程
首先,假設表中元素是按升序排列,將表中間位置記錄的關鍵字與查詢關鍵字比較,如果兩者相等,則查詢成功;否則利用中間位置記錄將表分成前、後兩個子表,如果中間位置記錄的關鍵字大於查詢關鍵字,則進一步查詢前一子表,否則進一步查詢後一子表。重複以上過程,直到找到滿足條件的記錄,使查詢成功,或直到子表不存在為止,此時查詢不成功。
程式碼
package cn.guizimo.search; public class BinarySearch { public static void main(String[] args) { int[] arr = {1, 5, 26, 68, 100, 235, 667, 896, 999}; int index = binarySearch(arr, 0, arr.length - 1, 26); if(index == -1){ System.out.println("未找到"); }else { System.out.println("下標為:"+index); } } public static int binarySearch(int[] arr, int left, int right, int value) { if (left > right) { return -1; } int mid = (right + left) / 2; int midValue = arr[mid]; if (value > midValue) { return binarySearch(arr, mid + 1, right, value); } else if (value < midValue) { return binarySearch(arr, left, mid - 1, value); } else { return mid; } } }
優化
將數列中重複的數的下標全部找到
程式碼
package cn.guizimo.search; import java.util.ArrayList; import java.util.List; public class BinarySearch { public static void main(String[] args) { int[] arr = {1, 5, 26, 26, 26, 26, 68, 100, 235, 667, 896, 999}; List<Integer> arrayList = binarySearch(arr, 0, arr.length - 1, 25); if (arrayList.size() == 0) { System.out.println("未找到"); } else { System.out.println("下標集為:" + arrayList); } } public static List<Integer> binarySearch(int[] arr, int left, int right, int value) { if (left > right) { return new ArrayList<Integer>(); } int mid = (left + right) / 2; int midValue = arr[mid]; if (value > midValue) { return binarySearch(arr, mid + 1, right, value); } else if (value < midValue) { return binarySearch(arr, left, mid - 1, value); } else { List<Integer> resIndexList = new ArrayList<Integer>(); int temp = mid - 1; while (true) { if (temp < 0 || arr[temp] != value) { break; } resIndexList.add(temp); temp -= 1; } resIndexList.add(mid); temp = mid + 1; while (true) { if (temp > arr.length - 1 || arr[temp] != value) { break; } resIndexList.add(temp); temp += 1; } return resIndexList; } } }
感謝
尚矽谷
百度百科
萬能的網路
以及勤勞的自己
關注公眾號: 歸子莫,獲取更多的資料,還有更長的學習計劃