|
23 | 23 | * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
|
24 | 24 |
|
25 | 25 |
|
26 |
| -(* |
27 |
| - [lower, upper) |
28 |
| - when [lower] = [upper], impossible |
29 |
| - [upper - lower] = 1 |
30 |
| - [mid = lower], it should hit |
31 |
| - [uper -lower > 1], [mid <> lower] |
32 |
| - *) |
33 |
| -let rec binarySearchAux lower upper xs (k : string) = |
34 |
| - if not (lower < upper) then Js_exn.raiseError "binarySearchAux"; |
35 |
| - let mid = (lower + upper) / 2 in |
36 |
| - let i,v = Js_array2.unsafe_get xs mid in |
37 |
| - if i = k then v |
38 |
| - else if i < k then |
39 |
| - binarySearchAux (mid + 1) upper xs k |
40 |
| - else |
41 |
| - binarySearchAux lower mid xs k (*Invariant: mid < upper *) |
42 |
| - |
43 |
| - |
44 |
| - |
45 |
| -let binarySearch upper (id : string) array : string = |
46 |
| - binarySearchAux 0 upper array id |
47 |
| - |
48 |
| -let rec revSearchAux |
49 |
| - i len (xs : ('a * string) array) (k : string) = |
50 |
| - if i = len then None |
51 |
| - else |
52 |
| - let (idx,s) = Js.Array2.unsafe_get xs i in |
53 |
| - if s = k then |
54 |
| - Some (idx : string) |
55 |
| - else |
56 |
| - revSearchAux (i + 1) len xs k |
57 |
| - |
58 |
| -let revSearch len array (x : string) : _ option = |
59 |
| - revSearchAux 0 len array x |
60 |
| - |
61 |
| -let rec revSearchAssertAux len |
62 |
| - i (xs : (_ * string) array) (k : string) = |
63 |
| - [%assert i < len]; |
64 |
| - let (idx,s) = Js.Array2.unsafe_get xs i in |
65 |
| - if s = k then |
66 |
| - idx |
67 |
| - else |
68 |
| - revSearchAssertAux len (i + 1) xs k |
69 | 26 |
|
70 |
| -let revSearchAssert len array (x : string) = |
71 |
| - revSearchAssertAux len 0 array x |
72 | 27 |
|
73 | 28 | let toInt (i : int) (xs : int array) =
|
74 | 29 | Js.Array2.unsafe_get xs i
|
|
0 commit comments