在C#中實(shí)現(xiàn)二分查找算法可以通過(guò)以下代碼示例:
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");
}
}
}
在上面的示例中,我們定義了一個(gè)binarySearch
方法用于實(shí)現(xiàn)二分查找算法。在Main
方法中,我們定義了一個(gè)有序的整數(shù)數(shù)組arr
和要查找的目標(biāo)值target
。然后調(diào)用binarySearch
方法進(jìn)行查找,并輸出結(jié)果。