Notes-TheAlgorithmDesignManual/binary_search.org

369 B

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;;