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
Published at
2026-10-08 15:07:22 UTCEvent JSON
{
"id": "1c4673c219e678dc532ee02fbc5c6dfb63b61bca46bd708f1d7b3d87f2b1367f",
"pubkey": "e68a0856e90d9997b1f721e905249896412dd570399a987b2e8fd5e7fcfe2279",
"created_at": 1791472042,
"kind": 1,
"tags": [
[
"t",
"tip"
]
],
"content": "Learn: Binary search in one post\n\nOn 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).\n\n```csharp\nint[] a = { 1, 3, 5, 7, 9, 11 };\nint target = 7, lo = 0, hi = a.Length - 1;\nwhile (lo \u003c= hi)\n{\n int mid = lo + (hi - lo) / 2;\n if (a[mid] == target) { Console.WriteLine(mid); break; }\n if (a[mid] \u003c target) lo = mid + 1; else hi = mid - 1;\n}\n```\n\nIt prints 3. Write mid as lo + (hi - lo) / 2: plain (lo + hi) / 2 can overflow an int on huge arrays.\n\n#tip · TIP-006",
"sig": "09beb8d3d213c2859905b1c95e66ee8b5df52528dd6ab1c51b92a766571cd5256551cfbfec60f3e64be4042b8b2f317b50ea78921b86252bfd8274fd995785af"
}