SoFunction
Updated on 2025-03-07

C# binary search algorithm example analysis

This article describes the C# binary search algorithm. Share it for your reference. The specific implementation method is as follows:

// input array is assumed to be sorted
public int BinarySearch(int[] arr, int x)
{
 if ( == 0)
  return -1;
 int mid =  / 2;
 if (arr[mid] == x)
  return mid;
 if (x < arr[mid])
  return BinarySearch(GetSubArray(arr,0,mid-1),x);
 else
 {
  int _indexFound = BinarySearch(GetSubArray(arr,mid+1,-1),x);
  if (_indexFound == -1)
   return -1;
  else
   return mid + 1 + BinarySearch(GetSubArray(arr,mid+1,-1),x);
 }
}
public int[] GetSubArray(int[] arr, int start, int end)
{
 List<int> _result = new List<int>();
 for (int i = start; i <= end; i++)
 {
  _result.Add(arr[i]);
 }
 return _result.ToArray();
}

I hope this article will be helpful to everyone's C# programming.