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.
Try each step
Section titled “Try each step”INTERACTIVE / LIVE
Live demoBinary search stepper
Pick a target, step forward and watch the search range change.
Implementation in C#
Section titled “Implementation in C#”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.