二分查詢java程式碼實現
阿新 • • 發佈:2019-02-02
public static void main(String[] args) { Integer[] arr = new Integer[]{12,15,20,36,45,66,72,81,90}; int des = 22; int search = binarySearch(arr, des); System.out.println(search); int recursive = binarySearchRecursive(arr, 0 , arr.length-1 ,des); System.out.println(recursive); } /** * 二分查詢 非遞迴 如果陣列中不存在要查詢的數返回-1 * * @param arr * @param des * @return */ public static int binarySearch(Integer[] arr, int des){ int start = 0; int end = arr.length-1; while (start <= end) { int middle = (( end - start )>>1)+ start; if (des == arr[middle]) { return middle+1; }else if (des < arr[middle]) { end = middle-1; }else if (des > arr[middle]) { start = middle+1; } } return -1; } /** * 二分查詢 遞迴方式 如果陣列中不存在要查詢的數返回-1 * * @param args * @param des * @return */ public static int binarySearchRecursive(Integer[] args ,int start, int end, int des){ int middle = -1; if (start <= end) { middle = (start + end) >> 1; if (des == args[middle]) { return middle+1; }else if (des < args[middle]) { end = middle -1; return binarySearchRecursive(args, start, end, des); }else if (des > args[middle]) { start = middle +1; return binarySearchRecursive(args, start, end, des); } } return middle; }