如何递归地编写插值搜索? - C#

时间:2018-05-12 10:42:35

标签: c# arrays recursion search interpolation

我需要编写一个递归函数,使用插值方法在数组中查找元素。优选地,它应该基于递归。

这是我的代码:

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。

有什么问题?

1 个答案:

答案 0 :(得分:0)

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

只需交换InterpolationSearch(arr, value, index + 1, right)InterpolationSearch(arr, value, left, index - 1)个功能。