int BinarySearch(int[] nums, int target)
{
if(nums == null || nums.Length == 0)
return -1;
int left = 0, right = nums.Length - 1;
while(left <= right)
{
// Prevent (left + right) overflow
int mid = left + (right - left) / 2;
if(nums[mid] == target)
{
return mid;
}
else if(nums[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
// End Condition: left > right
return -1;
}
// C# implementation of recursive Binary Search
using System;
class GFG {
// Returns index of x if it is present in
// arr[l..r], else return -1
static int binarySearch(int[] arr, int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the
// middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present
// in array
return -1;
}
// Driver method to test above
public static void Main()
{
int[] arr = { 2, 3, 4, 10, 40 };
int n = arr.Length;
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
if (result == -1)
Console.WriteLine("Element not present");
else
Console.WriteLine("Element found at index "
+ result);
}
}
// This code is contributed by Sam007.
using System;
public class Program
{
public static void Main()
{
int[] arr = new int[] {1, 2, 3, 4, 4, 5, 6, 7, 7, 7, 7, 8};
int query = 7;
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)
{
while(lo<=hi)
{
int mid = (lo+hi)/2;
string result = cond(mid);
if(result=="found") return mid;
else if(result=="left") hi = mid-1;
else lo=mid+1;
}
return -1;
}
public static int Find(int[] arr, int query)
{
int lo = 0;
int hi = arr.Length-1;
string CondLeft(int mid)
{
if(arr[mid]==query)
{
return "found";
}
else if(arr[mid]>query)
{
return "left";
}
else return "right";
}
return GenericBinarySearch(lo, hi, CondLeft);
}
public static int FindLeft(int[] arr, int query)
{
int lo = 0;
int hi = arr.Length-1;
string CondLeft(int mid)
{
if(arr[mid]==query)
{
if(mid-1>0 && arr[mid-1]==query) return "left";
return "found";
}
else if(arr[mid]>query)
{
return "left";
}
else return "right";
}
return GenericBinarySearch(lo, hi, CondLeft);
}
public static int FindRight(int[] arr, int query)
{
int lo = 0;
int hi = arr.Length-1;
string CondLeft(int mid)
{
if(arr[mid]==query)
{
if(mid+1<arr.Length && arr[mid+1]==query) return "right";
return "found";
}
else if(arr[mid]>query)
{
return "left";
}
else return "right";
}
return GenericBinarySearch(lo, hi, CondLeft);
}
}