Posted By

rtperson on 11/30/12


Tagged


Versions (?)

Binary Search in Haskell


 / Published in: Haskell
 

Not the best binary search implementation -- it really should return a Maybe, Nothing if value not found and Just value if found -- but it was a quick experiment for an evening, and it was cool to see how easily it translated from Java to Haskell.

  1. module BinarySearch where
  2.  
  3. a :: [Int]
  4. a = [6, 13, 14, 25, 33, 43, 51, 53, 64, 72, 84, 93, 95, 96, 97]
  5.  
  6. bsearch :: Int -> [Int] -> Int
  7. bsearch _ [] = -1
  8. bsearch key xs
  9. | key < val = bsearch key (take (mid-1) xs)
  10. | key > val = bsearch key (drop (mid+1) xs)
  11. | otherwise = val
  12. where
  13. mid = floor ((fromIntegral $ (length xs) - 1) / 2)
  14. val = xs !! mid

Report this snippet  

You need to login to post a comment.