Join Nostr
2026-10-08 15:07:22 UTC

codementor on Nostr: Learn: Binary search in one post On a sorted array, look at the middle. If the target ...

Learn: Binary search in one post

On a sorted array, look at the middle. If the target is bigger, keep the right half; if smaller, the left half. Each step halves the range: O(log n).

```csharp
int[] a = { 1, 3, 5, 7, 9, 11 };
int target = 7, lo = 0, hi = a.Length - 1;
while (lo <= hi)
{
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) { Console.WriteLine(mid); break; }
if (a[mid] < target) lo = mid + 1; else hi = mid - 1;
}
```

It prints 3. Write mid as lo + (hi - lo) / 2: plain (lo + hi) / 2 can overflow an int on huge arrays.

#tip · TIP-006