public static void Main()
int[] arr = new int[] {1, 2, 3, 4, 4, 4, 5, 6, 7, 7, 7, 7, 8};
Console.WriteLine(Find(arr, query));
Console.WriteLine(FindLeft(arr, query));
Console.WriteLine(FindRight(arr, query));
public delegate string Condition(int mid);
public static int GenericBinarySearch(int lo, int hi, Condition cond)
string result = cond(mid);
if(result=="found") return mid;
else if(result=="left") hi = mid-1;
public static int Find(int[] arr, int query)
return GenericBinarySearch(lo, hi, CondLeft);
public static int FindLeft(int[] arr, int query)
if(mid-1>0 && arr[mid-1]==query) return "left";
return GenericBinarySearch(lo, hi, CondLeft);
public static int FindRight(int[] arr, int query)
if(mid+1<arr.Length && arr[mid+1]==query) return "right";
return GenericBinarySearch(lo, hi, CondLeft);