【问题标题】:How to write interpolation search recursively? - C#如何递归地编写插值搜索? - C#
【发布时间】:2018-10-22 15:20:11
【问题描述】:

我需要编写一个递归函数,使用插值方法在数组中查找元素。最好是基于递归。

这是我的代码:

static int? InterpolationSearch(int[] arr, int value, int left, int right)
{
    if (arr[left] == value) return left;
    else if (left == right || arr[left] == arr[right]) return null;

    int index = left + (value - arr[left]) * (right - left) / (arr[right] - arr[left]);

    if (arr[index] == value) return index;
    else if (arr[left] < value) return InterpolationSearch(arr, value, index + 1, right);
    else return InterpolationSearch(arr, value, left, index - 1);
}

在大数组(大约 1000 个元素或更多)中搜索时,会抛出 StackOverflowException。

有什么问题?

【问题讨论】:

标签: c# arrays recursion search interpolation


【解决方案1】:

我找到了解决方案。这只是我的疏忽。

只需要交换 InterpolationSearch(arr, value, index + 1, right)InterpolationSearch(arr, value, left, index - 1) 函数。

【讨论】:

    【解决方案2】:

    似乎您从未退出该功能,这是另一个如何实现此功能的示例,它对我有用:

    public static int InterpolationSearch(int[] array, int value)
    {
        int low = 0;
        int high = array.Length - 1;
        return InterpolationSearch(array, value, ref low, ref high);
    }
    
    private static int InterpolationSearch(int[] array, int value, ref int low, ref int high)
    {
        int index = -1;
    
        if (low <= high)
        {
            index = (int)(low + (((int)(high - low) / (array[high] - array[low])) * (value - array[low])));
            if (array[index] == value) 
            {
                return index;
            }
            else
            {
                if (array[index] < value)
                    low = index + 1;
                else
                    high = index - 1;
            } 
    
            return InterpolationSearch(array, value, ref low, ref high);
        }
    
        return index;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-16
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 2019-11-04
      相关资源
      最近更新 更多