C# program to do a recursive binary search in an array
Here's a C# program that performs a recursive binary search in an array:
using System;
class Program
{
static void Main()
{
int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
int target = 12;
int result = BinarySearchRecursive(arr, target, 0, arr.Length - 1);
if (result == -1)
{
Console.WriteLine("Element not found in the array.");
}
else
{
Console.WriteLine("Element found at index " + result);
}
}
static int BinarySearchRecursive(int[] arr, int target, int low, int high)
{
if (low > high)
{
return -1; // Element not found
}
int mid = (low + high) / 2;
if (arr[mid] == target)
{
return mid; // Element found at mid index
}
else if (arr[mid] < target)
{
// Recursive call on the right half of the array
return BinarySearchRecursive(arr, target, mid + 1, high);
}
else
{
// Recursive call on the left half of the array
return BinarySearchRecursive(arr, target, low, mid - 1);
}
}
}
In this program, we have the BinarySearchRecursive method that performs a recursive binary search on a sorted array. The method takes the array (arr), the target value to search for (target), the low index of the search range (low), and the high index of the search range (high) as parameters.
The base case of the recursion is when low becomes greater than high, indicating that the search range is empty and the element is not found. In this case, the method returns -1.
In the recursive case, we calculate the middle index of the search range using (low + high) / 2. We compare the element at the middle index (arr[mid]) with the target value. If they are equal, we have found the element and return the middle index.
If arr[mid] is less than the target value, it means the target value is in the right half of the array. We make a recursive call to BinarySearchRecursive with the updated search range of mid + 1 to high.
If arr[mid] is greater than the target value, it means the target value is in the left half of the array. We make a recursive call to BinarySearchRecursive with the updated search range of low to mid - 1.
The program initializes an array arr and a target value target. It calls the BinarySearchRecursive method with the array, target value, initial low index (0), and initial high index (arr.Length - 1). The returned index is then checked, and the appropriate message is displayed based on whether the element is found or not.
In the example above, the output would be:
Element found at index 5
The target value 12 is found at index 5 in the array.