File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
01_introduction_to_algorithms/ocaml Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change
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 ))
You can’t perform that action at this time.
0 commit comments