【发布时间】:2020-11-20 09:09:04
【问题描述】:
红宝石
def binary_search(arr, l, r, x)
if r >= 1 then
mid = l + (r - 1) / 2
if arr[mid] == x then
return mid
end
if arr[mid] > x then
return binary_search(arr, l, mid - 1, x)
end
return binary_search(arr, mid + 1, r, x)
end
return -1
end
Java
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the
// middle itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not present
// in array
return -1;
}
当 x(目标元素)位于排序数组的右半部分时,发生堆栈溢出,我在 Ruby 中收到此错误
SystemStackError (stack level too deep)
为什么这发生在 ruby 中而不是 java 中?我正在 irb 中运行程序。 java 实现直接来自这里https://www.geeksforgeeks.org/binary-search/。
【问题讨论】:
-
你的问题我不清楚。这两个程序有很大的不同,Ruby 程序有一个 bug 会导致无限递归,所以很明显,它遇到了堆栈溢出。
-
为什么是
if r >= 1?你的意思是if r >= l? -
你不使用Array#bsearch是因为这只是一个练习吗?
标签: java ruby recursion stack-overflow binary-search