二分查找(面试必会知识点)

//递归 public int recursionSearch(int[] arr, int key, int low, int high) { if(key < arr[low] || key > arr[high] || low > high) { return -1; }int mid = (low + high) / 2; if(key < arr[mid]) { return recursionSearch(arr, key, low, mid - 1); } else if(key > arr[mid]) { return recursionSearch(arr, key, mid + 1, high); } else { return mid; } }//迭代 public int commonSearch(int[] arr, int key) { int low = 0; int high = arr.length - 1; int mid = 0; if(key < arr[low] || key > arr[high] || low > high) { return -1; }while(low <= high) { mid = (low + high) / 2; if(key < mid) { high = mid - 1; } else if(key > mid) { low = mid + 1; } else { return mid; } }return -1; }

【二分查找(面试必会知识点)】

    推荐阅读