Advertisement
Guest User

binary search

a guest
Apr 4th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.12 KB | None | 0 0
  1. (* Using the binary search algorithm, an element can be found very quickly in a sorted array.
  2. Write a function find : string array -> string -> int such that find arr word is the index of the word in the sorted array arr if it occurs in arr or -1 if word does not occur in arr.
  3.  
  4. The number or array accesses will be counted, to check that you obtain the expected algorithmic complexity. Beware that you really perform the minimal number of accesses. For instance, if your function has to test the contents of a cell twice, be sure to put the result of the access in a variable, and then perform the tests on that variable. *)
  5.  
  6. let find (dict: string array) (word: string) : int =
  7.   let l = 0 in
  8.   let r = Array.length(dict) - 1 in
  9.   let rec bin (left: int) (right: int) : int =
  10.     if left > right then -1
  11.     else
  12.       let middle = (left + right) / 2 in
  13.       let mid_val = dict.(middle) in
  14.       if mid_val = word then middle
  15.       else if word > mid_val
  16.       then
  17.            let left = middle + 1 in
  18.            bin left right
  19.          else
  20.            let right = middle - 1 in
  21.            bin left right in
  22.   bin l r
  23. ;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement