Created
June 19, 2016 15:45
-
-
Save seantalts/6a65ef83722850136b809c161883326e to your computer and use it in GitHub Desktop.
trying to find first element with duplicates (doesn't work)
This file contains 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
{-# LANGUAGE ScopedTypeVariables #-} | |
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 && pivot' < needle = binarySearch haystack needle mid' hi | |
| pivot == needle && pivot' == needle = binarySearch haystack needle mid' hi | |
| pivot < needle && pivot' == needle = Just mid' | |
| otherwise = Just mid | |
where | |
mid = lo + (hi-lo) `div` 2 | |
mid' = mid + 1 | |
pivot = haystack!mid | |
pivot' = haystack!mid' | |
main :: Int -> IO () | |
main divisor = do | |
let size = 30 | |
a = array (0, size) [(i, i `div` divisor) | i <- [0..size]] | |
putStrLn $ "hi: " ++ show a | |
putStrLn $ "hi: " ++ show (binarySearch a 4 0 size) | |
-- main 5 | |
--hi: array (0,30) [(0,0),(1,0),(2,0),(3,0),(4,0),(5,1),(6,1),(7,1),(8,1),(9,1),(10,2),(11,2),(12,2),(13,2),(14,2),(15,3),(16,3),(17,3),(18,3),(19,3),(20,4),(21,4),(22,4),(23,4),(24,4),(25,5),(26,5),(27,5),(28,5),(29,5),(30,6)] | |
--hi: Just 24 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment