Binary Search

Target0
Set Target
FastSlow
Initializing...
Time Complexity
Best
O(1)O(1)
Average
O(log⁡n)O(\log n)
Worst
O(log⁡n)O(\log n)
Space Complexity
O(1)O(1)
StabilityFALSE
In-placeTRUE

Explanation

What is Binary Search?

Binary Search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you've narrowed down the possible locations to just one.

Steps

  1. Compare the target value to the middle element of the array.
  2. If the target value matches the middle element, its position has been found.
  3. If the target value is less than the middle element, the search continues in the lower half of the array.
  4. If the target value is greater than the middle element, the search continues in the upper half of the array.

Complexity

  • Time Complexity: O(log⁡n)O(\log n)
  • Space Complexity: O(1)O(1)

Pseudo Code

1left = 0, right = length - 1
2while left <= right
3 mid = floor((left + right) / 2)
4 if array[mid] == target
5 return mid
6 else if array[mid] < target
7 left = mid + 1
8 else
9 right = mid - 1
Sponsor Ad