Medium csharp

DS — binary search index #69

Problem

Binary search for 13 in sorted 1..26.

Hints
  • mid = lo + (hi-lo)/2

Your solution

TestStatusDetails
Ready — edit the code above and click Run or Submit.

Solution

using System;

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, 25, 26 };
        int target = 13, 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.

Explanation

O(log n) search on sorted array.

Discussion

0

Sign in to join the discussion.

No discussions yet — ask the first question!

Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details