Sorted array 1..24; find index of 12 or -1.
| Test | Status | Details |
|---|
Ready — edit the code above and click Run or Submit.
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 };
int target = 12, lo = 0, hi = a.Length - 1, ans = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == target) { ans = mid; break; }
if (a[mid] < target) lo = mid + 1; else hi = mid - 1;
}
Console.WriteLine(ans);
}
}
Try solving on your own first, then reveal the official answer.
Standard binary search.