为什么这个binary_search函数不返回5?

时间:2013-03-30 13:50:04

标签: f#

这个f#程序对int数组进行二进制搜索,以查找第一次出现的数字。一旦找到数字,它就会打印出位置,然后返回它。然后它打印返回值,但打印不同的数字。我期待相同的数字。为什么会有所不同?

let int_array = [| 1; 3; 3; 4; 4; 5; 5; 6; 6; 6; 6; 6; 6; 6; 6; 6; 6; 6; 8; 9|]

let binary_search target (array:int[]) = 
    let rec bsearch found_pos start_i end_i  =
        let mid_i = start_i + (end_i-start_i) / 2
        if start_i = end_i then
            printfn "answer is %d" found_pos
            found_pos
        elif array.[ mid_i ] = target then
            bsearch mid_i start_i mid_i-1 
        elif array.[ mid_i ] < target then
            bsearch found_pos (mid_i+1) end_i
        else
            bsearch found_pos start_i (mid_i-1)
    bsearch -1 0 ((Array.length array)-1)


let ans = binary_search 5 int_array
printfn "but it returns %d" ans

这是输出:

answer is 5
but it returns 3

1 个答案:

答案 0 :(得分:6)

您的问题缺少括号。代码bsearch mid_i start_i mid_i-1(bsearch mid_i start_i mid_i)-1相同。如果将其更改为bsearch mid_i start_i (mid_i-1),则第一个和最终结果将相同。