Created
March 8, 2018 10:06
-
-
Save samidarko/221e6426d6a498e9116d80271af881ad to your computer and use it in GitHub Desktop.
binary search function in Haskell for Int lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
binarySearch :: Ord a => a -> [a] -> Maybe Int | |
binarySearch s xs = let left = 0 | |
right = length xs - 1 | |
in fn left right | |
where fn l r = if l > r | |
then Nothing | |
else let m = (l + r) `div` 2 | |
e = xs !! m | |
in if e < s | |
then fn (m+1) r | |
else if e > s | |
then fn l (m-1) | |
else Just m |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment