在C#中实现二分查找算法可以通过以下代码示例:
using System;
class BinarySearch
{
static int binarySearch(int[] arr, int target)
{
int left = 0;
int right = arr.Length - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] == target)
{
return mid;
}
else if (arr[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
static void Main()
{
int[] arr = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };
int target = 12;
int result = binarySearch(arr, target);
if (result != -1)
{
Console.WriteLine("Element found at index " + result);
}
else
{
Console.WriteLine("Element not found");
}
}
}
在上面的示例中,我们定义了一个binarySearch
方法用于实现二分查找算法。在Main
方法中,我们定义了一个有序的整数数组arr
和要查找的目标值target
。然后调用binarySearch
方法进行查找,并输出结果。