使用阈值进行二进制搜索

时间:2015-01-05 02:39:34

标签: matlab search binary-search

我有一个我要搜索的有序列表,但我没有在列表中查找特定值。我有一个阈值,想要找到大于该值的所有值。

例如,如果我有列表2 4 6 8 10 12 14 16 18 20,我正在搜索索引,该索引返回所有大于特定数字的值,如13。

这是我的代码的样子,但它并不适用于所有情况。例如,如果我有一个2 20的列表并且查找大于10的数字,则代码会被卡住。我试图找到一个优雅的解决方案来解决这些问题而不添加一堆if循环来检查特定情况,因为我将在最多8个列表上运行此函数1000万次!长,所以效率是关键。任何建议将不胜感激。

% Note that permutations represents my ordered list of values

function [index] = binarySearch(permutations, threshold) 
    start = 1;
    stop = length(permutations);
    middle = floor((stop+start)/2);
    while(stop-start > 0)
        if(permutations(middle) > threshold)
            stop = middle;
        elseif(permutations(middle) < threshold)
            start = middle;
        elseif(permutations(middle) == threshold)
            index = middle;
            return;
        end
        if(stop == 1)
            index = 0;
            return;
        end
        middle = floor((stop+start)/2);
    end
    index = middle;
end

0 个答案:

没有答案
相关问题