1 (* Copyright (C
) 1999-2005 Henry Cejtin
, Matthew Fluet
, Suresh
2 * Jagannathan
, and Stephen Weeks
.
4 * MLton is released under a BSD
-style license
.
5 * See the file MLton
-LICENSE for details
.
8 structure BinarySearch
: BINARY_SEARCH
=
11 (* Based on page
38 of Programming Pearls
, by Jon Bentley
. *)
12 fun 'a
search (a
: 'a array
, f
: 'a
-> order
): int option
=
14 fun loop (min
: int, max
: int): int option
=
18 let val mid
= Int.quot (min
+ max
, 2)
19 in case f (Array
.sub (a
, mid
)) of
20 LESS
=> loop (min
, mid
- 1)
22 | GREATER
=> loop (mid
+ 1, max
)
24 in loop (0, Array
.length a
- 1)
27 fun 'a
largest (a
: 'a array
, f
: 'a
-> bool): int option
=
29 fun loop(min
, max
, res
: int option
): int option
=
33 let val mid
= Int.quot(min
+ max
, 2)
34 in if f(Array
.sub(a
, mid
))
35 then loop(mid
+ 1, max
, SOME mid
)
36 else loop(min
, mid
- 1, res
)
38 in loop(0, Array
.length a
- 1, NONE
)
41 fun 'a
smallest(a
: 'a array
, f
: 'a
-> bool): int option
=
43 fun loop(min
, max
, res
: int option
): int option
=
47 let val mid
= Int.quot(min
+ max
, 2)
48 in if f(Array
.sub(a
, mid
))
49 then loop(min
, mid
- 1, SOME mid
)
50 else loop(mid
+ 1, max
, res
)
52 in loop(0, Array
.length a
- 1, NONE
)