Fix haskell binarysearch (#51)

This commit is contained in:
Aliaksandr
2018-02-03 22:56:41 +03:00
committed by Aditya Bhargava
parent 1fa164c40e
commit b515434b3f

View File

@@ -3,19 +3,20 @@ import Data.Array
binarysearch :: Integer -> Array Integer Integer -> Integer -> Integer -> Maybe Integer
binarysearch x arr low high
| low > high = Nothing
| mid > x = binarysearch x arr low (high - 1)
| mid < x = binarysearch x arr (low + 1) high
| guess > x = binarysearch x arr low (mid - 1)
| guess < x = binarysearch x arr (mid + 1) high
| otherwise = Just mid
where
mid = arr ! ((low + high) `div` 2)
mid = ((low + high) `div` 2)
guess = arr ! mid
find :: Integer -> Array Integer Integer -> Maybe Integer
find x arr = binarysearch x arr low high
where p = bounds arr
low = fst p
high = snd p
where borders = bounds arr
low = fst borders
high = snd borders
-- Usage
-- let arr = array (0, 4) [(i, i*i) | i <- [0..4]]
-- find 4 arr
-- let arr = array (0, 4) [(i, i*i) | i <- [0..4]] // [(0,0),(1,1),(2,4),(3,9),(4,16)]
-- find 4 arr // Just 2
-- find 25 arr // Nothing