二进制搜索无限递归

时间:2017-12-21 05:06:09

标签: matlab search binary-search

我在Matlab中为二进制搜索编写了简单的代码。如果搜索的项目在数组中,它会正常工作,但如果没有,则进入无限递归循环。

我不确定问题出在哪里。

val poolingOptions = new PoolingOptions()
    .setConnectionsPerHost(HostDistance.LOCAL, 1, 2)
    .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
    .setCoreConnectionsPerHost(HostDistance.LOCAL, 2)

2 个答案:

答案 0 :(得分:2)

想象一下,在列表中只有2个项目的非常简单的情况

A = [1 3]

并在BinarySearch上呼叫item,该BinarySearch(A, 1, 2, 2) % mid = 1 % item ~= A(1): go to else % item > A(1): go to else % BinarySearch(A, 1, 2, 2) % ... rinse and repeat 位于列表中间。请看下面的评论,这些评论遵循您的函数行为......

item

如果BinarySearch(A, 1, 2, 0) % mid = 1 % item ~= A(1): go to else % item < A(1) % BinarySearch(A, 1, 1, 0) % mid = 1 % beg <= last (this is still true) % item ~= A(1): go to else % item < A(1) % BinarySearch(A, 1, 1, 0) % ... rinse and repeat 太小

item

同样地,BinarySearch(A, 1, 2, 5) % leads to BinarySearch(A, 1, 2, 5) % ... repeat!! 大于列表中的任何一个,

beg

您不断重新检查相同的区域,因为您的左侧(last)和右侧(function idx = BinarySearch(A, L, R, item) %% BINARYSEARCH search for an item in the array A. Assumes that A is sorted ascending % 1. Should be initially called using idx = BinarySearch(A, 1, n, item) % where n is the number of elements in A, numel(A) % 2. if L > R, the search terminates as unsuccessful if L > R idx = 0; else % 3. set m (position of middle element) to the floor of (L+R)/2 m = floor((L+R)/2); % 4. if Am < item, set L to m+1 and go to 2. if A(m) < item L = m + 1; % YOU MISSED THIS STEP, CAUSING OVERLAPPING SEARCH REGIONS idx = BinarySearch(A, L, R, item); % 5. if Am > item, set R to m-1 and go to 2. elseif A(m) > item R = m - 1; % THE OTHER HALF OF THE STEP YOU MISSED idx = BinarySearch(A, L, R, item); % 6. Now Am = item, search is done, return index else idx = m; end end end )索引都可以保持不变。

让我们重新实现该功能,返回一个实际值,而不是仅仅将位置打印到控制台。评论与Wikipedia article for binary search中的编号步骤直接相关,其结构与您尝试的内容相似:

A

像以前一样使用BinarySearch(A, 1, 2, 2); % returns 0: not found BinarySearch(A, 1, 2, 0); % returns 0: not found BinarySearch(A, 1, 2, 5); % returns 0: not found BinarySearch(A, 1, 2, 3); % returns 2: 3 is at index 2 BinarySearch(A, 1, 2, 1); % returns 1: 1 is at index 1 进行测试:

while

请注意,递归实现此方法可能效率最高。我将把它留作练习,但可以使用$dom = new IvoPetkov\HTML5DOMDocument(); $dom->loadHTML('<!DOCTYPE html><html><body><h1>Hello</h1><div class="content">This is some text</div></body></html>'); echo $dom->querySelector('h1')->innerHTML; 循环轻松实现。将使用相同的逻辑结构。

答案 1 :(得分:1)

尝试设置断点以检查您认为可能存在问题的值。

您可以使用while循环和break命令来避免进入无限循环。

例如尝试这样的事情:

private bool AreAnyInteractablesInThisList<T>(IEnumerable<T> Interactables, T InteractableToCheck) where T : IInteractable
{
    // I cache this ID (assuming it was not changing with each call)
    int idToCheck = InteractableToCheck.GetInstanceID();
    return Interactables.Any(interactable => interactable.GetInstanceID() == idToCheck);
}