Source
Source Address
public static int binarySearch(int[] a, int key) { return binarySearch0(a, 0, a.length, key); } public static int binarySearch(int[] a, int fromIndex, int toIndex, int key) { rangeCheck(a.length, fromIndex, toIndex); return binarySearch0(a, fromIndex, toIndex, key); } // Like public version, but without range checks. private static int binarySearch0(int[] a, int fromIndex, int toIndex, int key) { int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high) >>> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. }
Thinking
Why is mid + 1, mid-1 on a subscript feel not bad ah.
Answer: After debugging and then recall, found that there is no difference, the final collapse to low = = high when all can be calculated, will not miss.
Code of your own hand
public class Source1_binarysearch {public static int binarysearch (int[] A, int fromIndex, int toindex, int key) { int low = FromIndex; int high = toIndex-1; while (low <= high) {int mid = (low + high) >> 1; int midvalue = A[mid]; Less than lo points to the middle, greater than hi to the middle, equals directly to return if (Midvalue < key) Low = mid + 1; else if (Midvalue > key) high = mid-1; else return mid; } return-1; } public static int binarysearch_recursive (int[] A, int fromIndex, int. toindex, int key) {int low = FromIndex; int high = toIndex-1; int result =-1; if (low <=) {int mid = (low + high) >>> 1; int midvalue = A[mid]; if (Midvalue < key) result = Binarysearch_recursive (a,mid +1,high + 1,key); else if (Midvalue > key) result = BinarYsearch_recursive (A,low,mid + 1-1,key); else return mid; } return result; public static void Main (string[] args) {int[] a = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int index = binarysearch_recursive (A, 0, a.length, 11); SYSTEM.OUT.PRINTLN (index); }}
Java source Code Analysis (1): Binary lookup + cyclic recursive implementation