Easy csharp

Binary search index of 6 #50

Problem

Sorted array 1..12; find index of 6 or -1.

Hints
  • lo + (hi-lo)/2 to avoid overflow

Your solution

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

Solution

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 };
        int target = 6, 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

Standard binary search.

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