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[] arr, int target) {2 int left = 0, right = arr.length - 1; // Full search range3 while (left <= right) { // While range non-empty4 int mid = (left + right) / 2; // Middle index5 if (arr[mid] == target) return mid; // Match found6 else if (arr[mid] < target) left = mid + 1; // Discard left half7 else right = mid - 1; // Discard right half8 }9 return -1; // Not in array10}