Binary Search — DSA Interview 150 · Binary Search
Classic interview problem #704.
Input (stdin)
Line 1: sorted array\nLine 2: target
Output (stdout)
Index or -1
Your program must read from stdin and write the answer to stdout (no extra debug text).
-1 0 3 5 9 12 9
4
| Test | Status | Details |
|---|
Ready — edit the code above and click Run or Submit.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static int[] Ria(string line = null)
{
line ??= Console.ReadLine();
if (string.IsNullOrWhiteSpace(line)) return Array.Empty<int>();
return line.Trim().Split(new[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
}
static string[] Rsa()
{
int n = int.Parse(Console.ReadLine());
var arr = new string[n];
for (int i = 0; i < n; i++) arr[i] = Console.ReadLine();
return arr;
}
static void W(params object[] parts) => Console.WriteLine(string.Join(" ", parts));
static void Wb(bool v) => Console.WriteLine(v ? "true" : "false");
static void Wi(int v) => Console.WriteLine(v);
static void Ws(string v) => Console.WriteLine(v);
static void Main()
{
var nums = Ria();
int target = int.Parse(Console.ReadLine());
int lo = 0, hi = nums.Length - 1, ans = -1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) { ans = mid; break; }
if (nums[mid] < target) lo = mid + 1; else hi = mid - 1;
}
Wi(ans);
}
}
Try solving on your own first, then reveal the official answer.
Pattern: Binary Search
Read from stdin, write to stdout. Classic interview problem #704.