OCaml中的二进制搜索?

时间:2014-03-02 05:23:54

标签: ocaml binary-search

有人可以告诉我这里的错误在哪里吗?

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中的二进制搜索有任何建议,请通知我?

2 个答案:

答案 0 :(得分:1)

您的问题是您在首先定义之前使用了例外。将exception Found_It ...行移到let binary_search ...行上方。

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

答案 1 :(得分:0)

异常Found_It of int ;; (*这里我们声明一个“异常”。这是一个特殊的工具,可以让我们打破循环。)                                      (此特殊异常采用整数作为参数。*)

让binary_search数组大小为x =   设n = size-1 in(*让不可变变量n存储数组的最终索引)   让p = ref 0 in(让minpoint q等于0 )   令r = ref n in(让maxpoint 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"             *)

with Found_It(x) - &gt; X;; (*如果我们用q打破了循环,输出q *)