Binary search
Return the index of a target in a sorted integer array, or -1 when the target is absent.
Course progress
Problem 9 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [2, 5, 8, 12, 16, 23]; target = 12
Expected output
3
What is happening?
Binary search narrows the sorted array around its middle positions and finds 12 at zero-based index 3.
Solution strategy
Build the right mental model
Compare the target with the middle item and discard the half that cannot contain it. The input must already be sorted.
Core concepts
search · sorted arrays
Complexity
Time O(log n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for binary-search
using System;
class Program
{
static int BinarySearch(int[] numbers, int target)
{
int low = 0;
int high = numbers.Length - 1;
while (low <= high)
{
int middle = low + (high - low) / 2;
if (numbers[middle] == target) return middle;
if (numbers[middle] < target) low = middle + 1;
else high = middle - 1;
}
return -1;
}
static void Main()
{
Console.WriteLine(BinarySearch(new[] { 2, 5, 8, 12, 16, 23 }, 12));
}
}Knowledge check
Questions students often ask
What is the main idea behind binary search?
Compare the target with the middle item and discard the half that cannot contain it. The input must already be sorted.
What is the time and space complexity of this solution?
Time O(log n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.