斐波那契搜索算法抛出索引超出范围异常

问题描述 投票:0回答:1

我正在尝试实现斐波那契搜索算法。但即使在参考了可能的网站之后也无法弄清楚为什么下面的代码会抛出索引超出范围异常。不确定我的实现中是否存在一些错误。

Console.WriteLine("Fibonacci Search!");

int[] nums = { 1,2, 4, 5, 7, 44, 90, 121, 144 };

 

Search _search = new Search();

 

int position = _search.FibonacciSearch(nums, 145);

 

if (position != -1)

    Console.WriteLine($"Element is present at index : {position}");

else

    Console.WriteLine("Element is not present in array");

 

public class Search

{

    public int FibonacciSearch(int[] arr, int x)

    {

        int n = arr.Length;

        int FibM2 = 0;

        int FibM1 = 1;

        int FibM = FibM1 + FibM2;

 

        while(FibM <= n)

        {

            FibM2 = FibM1;

            FibM1 = FibM;

            FibM = FibM1 + FibM2;

        }

 

        int offSet = -1;

 

        while (FibM2 > 0)

        {

            int index = Math.Min(offSet + FibM2, n - 1);

 

            if (arr[index] < x)

            {

                FibM = FibM1;

                FibM1 = FibM2;

                FibM2 = FibM - FibM1;

                offSet = index;

            }

            else if (arr[index] > x)

            {

                FibM = FibM2;

                FibM1 = FibM1 - FibM2;

                FibM2 = FibM - FibM1;

            }

            else

            {

                return index;

            }

        }

        if (FibM1 == 1 && arr[offSet + 1] == x)

            return (offSet + 1);

        return -1;

    }

 

}

当尝试使用数组中存在的某些元素时,斐波那契搜索算法起作用。但是,当尝试搜索数组中不存在的一些大数字时,它会抛出错误“最后一行的索引超出范围”

       if (FibM1 == 1 && arr[offSet + 1] == x)

c# algorithm search data-structures
1个回答
0
投票

一个简单的解决方案是将有问题的代码放在 try-catch 块中:

try
{
    
    if (FibM1 == 1 && arr[offSet + 1] == x)

        return (offSet + 1);
}
catch(IndexOutOfRangeException e)
{
    return -1;
}
© www.soinside.com 2019 - 2024. All rights reserved.