Advertisement
Guest User

binary search

a guest
Apr 4th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.03 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 (arr: string array) (word: string) : int =
  7.   let l = 0 in
  8.   let r = Array.length(arr) - 1 in
  9.   let rec bin (left: int) (right: int) : int =
  10.     let middle = (left + right) / 2 in
  11.     let mid_val = arr.(middle) in
  12.     if left > right then -1
  13.     else if mid_val = word then middle
  14.     else if word > mid_val
  15.     then
  16.       bin (middle + 1) right
  17.     else
  18.       bin left (middle - 1)
  19.   in bin l r
  20. ;;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement