Binary Search is an efficient algorithm for locating a target element in a sorted array by repeatedly dividing the search interval in half.
left to the start of the array and right to the end.mid = left + (right - left) / 2;
mid equals the target, return mid (target found).mid is less than the target, update left to mid + 1 to search the right half.mid is greater than the target, update right to mid - 1 to search the
left half.4.Repeat
left exceeds right.-1.| Scenario | Time Complexity | Explanation |
|---|---|---|
| Best Case | O(1) | The target is found at the middle in the first try. |
| Average Case | O(log n) | The search space is halved with each iteration. |
| Worst Case | O(log n) | Even in the worst case, the number of comparisons grows logarithmically. |
https://drawtocode.vercel.app/problems/binary-search
Loading component...
Loading component...