Skip to content

Instantly share code, notes, and snippets.

@seantalts
Created June 19, 2016 15:58
Show Gist options
  • Save seantalts/c9b3c1633d20352fd520f67503d0a497 to your computer and use it in GitHub Desktop.
Save seantalts/c9b3c1633d20352fd520f67503d0a497 to your computer and use it in GitHub Desktop.
Binary Search to find first occurrence with duplicates
module BinarySearch where
import Data.Array
binarySearch :: (Ord a1) => Array Int a1 -> a1 -> Int -> Int -> Maybe Int
binarySearch haystack needle lo hi
| hi < lo = Nothing
| pivot > needle = binarySearch haystack needle lo (mid-1)
| pivot < needle = binarySearch haystack needle (mid+1) hi
| lo /= mid = binarySearch haystack needle lo mid
| otherwise = Just mid
where
mid = lo + (hi-lo) `div` 2
pivot = haystack!mid
main :: Int -> IO ()
main divisor = do
let size = 30
a = array (0, size) [(i, i `div` divisor) | i <- [0..size]]
putStrLn $ "array: " ++ show a
putStrLn $ "bs: " ++ show (binarySearch a 4 0 size)
main 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment