【发布时间】: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。
有什么问题?
【问题讨论】:
-
你的递归调用次数过多;换句话说,你永远不会退出这个方法。这个方法抛出的最简单的输入是什么?
-
在方法中左右打印出来,方便调试代码。很可能 left 或 right 超出了数组的大小。
-
@Isma,都是非递归函数
-
使用此调用
InterpolationSearch(new int [] {10, 20, 30, 40}, 12 , 0, 3);进行调试。它将表现出相同的行为。
标签: c# arrays recursion search interpolation