在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
方法進行查找,并輸出結果。