2014-03-02 71 views
-1

有人能告诉我这里的错误在哪里?OCaml中的二进制搜索?

let a = [|2;4;6;9;12|];; 

a.(0);; 
a.(4);; 
a.(5);; 

let binary_search array size x = 
    let n = size-1 in 
    let p = ref 0 in 
    let r = ref n in 
    while (!p <= !r) do 
    let q = (!p + !r)/2;   
    if array.(q) = x 
    then raise ((Found_It (q));)      
    else if (array.(q) <> x) && (array.(q) > x) 
    then (r := q - 1;)    
    else if array.(q) < x 
    then (p := q + 1;) 
    done; 
    else -1;; 

exception Found_It of int;; 

如果您对ocaml中的二进制搜索有任何建议,请通知我?

+3

这与*** Emacs ***有什么关系?如果答案看起来像* nothing,那么考虑从标题中删除标签'emacs'和“emacs”。 – Drew

回答

1

您的问题是,您在第一次定义之前使用了异常。将exception Found_It ...行移动到let binary_search ...行以上。

另外,正如Drew所说,您的问题与Emacs完全无关。

+0

我还是有语法错误 – user1729430

0

异常Found_It int ;; (*这里我们声明一个“例外”,这是一个特殊的工具,它将使我们能够打破循环。) (这个特定异常需要一个整数作为参数。*)

让binary_search数组大小x = 令n =大小-1中(*让不变的变量n存储阵列的最终指数) 令p = REF 0(让minpoint q等于0 ) 设R = REF n的(让最大点r等于n *)

while !p <= !r do  
    let q = ref ((!p + !r)/2) in    (* calculate the midpoint for roughly equal partition *) 
    print_int !q; print_string " "; 
    if array.(!q) = x    (* if x is found at index p *) 
    then raise (Found_It (!q))  (* then break the loop with Found_It, which "carries" the value of q with it *)   
    else if array.(!q) > x   (* otherwise if q <> x and q > x *) 
    then r := !q - 1     (*change r index to search lower subarray*) 
    else p := !q + 1     (* otherwise if q < x change p index to search upper lower subarra *) 
done;        (* that's the end of the loop            *) 
-1; 

         (* so if we reach the end of the loop, output -1 for "Not found"    *) 

与Found_It(x) - > x ;; (*如果我们用q打破循环,输出q *)