二进制搜索返回错误的值

时间:2013-09-24 12:57:56

标签: ruby

我在Ruby中开发一个有效的二进制搜索算法时面临一些问题,参考this site

正确答案:返回值-1432
收到答案: Nil

代码如下:

def bsearch(a, k)

lower = 0
upper = a.length-1

while a[upper].to_f> k.to_f and a[lower].to_f< k.to_f
    low_diff = k.to_f -a[lower].to_f
    range_diff = a[upper].to_f-a[lower].to_f
    count_diff = upper-lower
    range = ((low_diff/range_diff) * (count_diff))  + lower

    if k.to_f > a[range].to_f
        lower = range+1
    elsif k.to_f <  a[range].to_f
        upper =range-1
    else    
        lower = range
    end 
end
if k =a[lower]
    return lower
else
    return nil
end
end

请帮我解决逻辑。

1 个答案:

答案 0 :(得分:0)

与@vacawama一样,在最后==条件中使用=代替if

if k == a[lower]  

&&条件中使用and代替while

while a[upper].to_f > k.to_f && a[lower].to_f < k.to_f  

我对此代码的输出:

more ./bsearch.rb
#!/usr/bin/ruby
def bsearch(a, k)
    lower = 0
    upper = a.length-1
    while a[upper].to_f > k.to_f && a[lower].to_f < k.to_f
        low_diff = k.to_f - a[lower].to_f
        range_diff = a[upper].to_f - a[lower].to_f
        count_diff = upper-lower
        range = ((low_diff / range_diff) * (count_diff))  + lower
        if k.to_f > a[range].to_f
            lower = range + 1
        elsif k.to_f <  a[range].to_f
            upper = range - 1
        else    
            lower = range
        end 
    end
    if k == a[lower]
        return lower
    else
        return nil
    end
end

puts bsearch([1, 2, 3, 4, 5], 3)

是:

./bsearch.rb
2.0