Notes-TheAlgorithmDesignManual/binary_search.org

16 lines
369 B
Org Mode

** OCaml
#+begin_src ocaml
let binary_search items target =
let rec f low high =
match (high - low) / 2 + low with
| mid when target = items.(mid) -> Some items.(mid)
| mid when target < items.(mid) -> f low mid
| mid when target > items.(mid) -> f mid high
| _ -> None
in f 0 (Array.length items);;
binary_search [|1;2;3;4;5|] 3;;
#+end_src