Data Structures and Algorithms • C# examples
Binary Search on Sorted Data
Repeatedly halve a sorted search interval to find a target in logarithmic time.
Concept
Binary search requires a monotonic ordering: after comparing with the midpoint, one half must be safely excluded. Inclusive and half-open interval conventions both work, but mixing their boundary updates causes common off-by-one errors. Use a midpoint expression that cannot overflow.
How to approach it
Maintain a candidate interval and a clear invariant; stop when the interval is empty or the target is found.
Complexity
O(log n) comparisons and O(1) iterative space.
C# example
static int BinarySearch(int[] sorted, int target)
{
int low = 0, high = sorted.Length;
while (low < high)
{
int mid = low + (high - low) / 2;
if (sorted[mid] < target) low = mid + 1;
else high = mid;
}
return low < sorted.Length && sorted[low] == target ? low : -1;
}
Expected result or behavior
This lower-bound variant returns the first matching index, or -1 when absent.
Practice exercise
Trace the algorithm for an empty array, one item, and duplicate target values.
Key takeaway: Binary search is about maintaining a shrinking valid interval, not merely checking a midpoint.