溫馨提示×

如何在C#中處理二分查找的異常情況

c#
小樊
82
2024-09-16 09:20:20
欄目: 編程語言

在C#中處理二分查找的異常情況,可以使用try-catch語句來捕獲和處理可能出現(xiàn)的異常

using System;

class BinarySearchExample
{
    static int BinarySearch(int[] arr, int target)
    {
        int left = 0;
        int right = arr.Length - 1;

        while (left <= right)
        {
            int mid = (left + right) / 2;

            if (arr[mid] == target)
                return mid;

            if (arr[mid]< target)
                left = mid + 1;
            else
                right = mid - 1;
        }

        return -1; // 如果未找到目標值,則返回-1
    }

    static void Main(string[] args)
    {
        int[] sortedArray = new int[] { 1, 3, 5, 7, 9 };
        int targetValue = 5;

        try
        {
            int index = BinarySearch(sortedArray, targetValue);

            if (index != -1)
                Console.WriteLine("Target value found at index: " + index);
            else
                Console.WriteLine("Target value not found in the array.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred during binary search: " + ex.Message);
        }
    }
}

在這個示例中,我們定義了一個BinarySearch方法來執(zhí)行二分查找。在Main方法中,我們調(diào)用BinarySearch方法并使用try-catch語句捕獲任何可能的異常。如果在二分查找過程中發(fā)生異常,我們可以在catch塊中處理它,例如打印錯誤消息。

需要注意的是,二分查找算法假設(shè)輸入數(shù)組是已排序的。如果輸入數(shù)組未排序,可能會導(dǎo)致不正確的結(jié)果或異常。在實際應(yīng)用中,請確保在使用二分查找之前對數(shù)組進行排序。

0