如何在C#中實(shí)現(xiàn)二分查找算法

c#
小樊
85
2024-08-21 08:39:29

在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é)果。

0