2014-03-02 24 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 *)