Skip to content

Binary search

Binary search finds a value in a sorted array by examining the middle element. Each comparison can remove about half the remaining candidates.

INTERACTIVE / LIVE

Binary search stepper

Pick a target, step forward and watch the search range change.

Live demo
SORTED ARRAY

Find a value by repeatedly halving the search range.

Select Next step to begin.

Step 0
C# | BinarySearch.cs
static int BinarySearch(int[] sorted, int target)
{
int left = 0;
int right = sorted.Length - 1;
while (left <= right)
{
int middle = left + (right - left) / 2;
if (sorted[middle] == target)
return middle;
if (sorted[middle] < target)
left = middle + 1;
else
right = middle - 1;
}
return -1;
}

The time complexity is O(log n) and this iterative implementation uses O(1) additional space.