Loading…
Loading…
On a sorted array, repeatedly halves the search range by comparing the middle element to the target — O(log n).
Search sorted array for 53.
Tip: click any bar to make it the target.
1int binarySearch(int[] a, int target) {2 int lo = 0, hi = a.length - 1;3 while (lo <= hi) {4 int mid = (lo + hi) / 2;5 if (a[mid] == target) return mid;6 else if (a[mid] < target) lo = mid + 1;7 else hi = mid - 1;8 }9 return -1;10}