Playground

Binary Search

Find an element in a sorted array by repeatedly halving the search interval.

Binary Search

Find an element in a sorted array by repeatedly halving the search interval. If the value is less than the middle element, narrow to the lower half.

Time O(log n)  |  Space O(1)  |  Divide & Conquer
Data
Target
Size7
Speed800ms
0
2
1
5
2
8
3
12
4
16
5
23
6
38
100%

BINARY SEARCH

left = 0, right = n - 1
while left <= right:
mid = floor((left + right) / 2)
if arr[mid] == target:
return mid
else if arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1

Console Output

Target = 12
>Press SEARCH to begin…