Skip to content

Commit 31412a0

Browse files
i-s-o-g-r-a-megonSchiele
authored andcommitted
Add binary search in OCaml (egonSchiele#90)
1 parent be4a420 commit 31412a0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
let rec binary_search ?(min = 0) ?(max = None) seq target =
2+
let max_ = match max with None -> Array.length seq - 1 | Some i -> i in
3+
if min > max_ then None
4+
else if Array.length seq = 0 then None
5+
else
6+
let mid = (max_ + min) / 2 in
7+
let current = seq.(mid) in
8+
if current = target then Some mid
9+
else if current > target then
10+
binary_search ~min ~max:(Some (mid - 1)) seq target
11+
else
12+
binary_search ~min:(mid + 1) ~max seq target
13+
14+
let print_result result =
15+
match result with
16+
| None -> print_endline "not found"
17+
| Some i -> print_string "found: " ; print_int i ; print_newline ()
18+
19+
let my_list = [|1; 3; 5; 7; 9|]
20+
21+
(* 1 *)
22+
let () = print_result (binary_search my_list 3)
23+
24+
(* None *)
25+
let () = print_result (binary_search my_list (-1))

0 commit comments

Comments
 (0)