Fix haskell binarysearch (#51)
This commit is contained in:
committed by
Aditya Bhargava
parent
1fa164c40e
commit
b515434b3f
@@ -3,19 +3,20 @@ import Data.Array
|
|||||||
binarysearch :: Integer -> Array Integer Integer -> Integer -> Integer -> Maybe Integer
|
binarysearch :: Integer -> Array Integer Integer -> Integer -> Integer -> Maybe Integer
|
||||||
binarysearch x arr low high
|
binarysearch x arr low high
|
||||||
| low > high = Nothing
|
| low > high = Nothing
|
||||||
| mid > x = binarysearch x arr low (high - 1)
|
| guess > x = binarysearch x arr low (mid - 1)
|
||||||
| mid < x = binarysearch x arr (low + 1) high
|
| guess < x = binarysearch x arr (mid + 1) high
|
||||||
| otherwise = Just mid
|
| otherwise = Just mid
|
||||||
where
|
where
|
||||||
mid = arr ! ((low + high) `div` 2)
|
mid = ((low + high) `div` 2)
|
||||||
|
guess = arr ! mid
|
||||||
|
|
||||||
find :: Integer -> Array Integer Integer -> Maybe Integer
|
find :: Integer -> Array Integer Integer -> Maybe Integer
|
||||||
find x arr = binarysearch x arr low high
|
find x arr = binarysearch x arr low high
|
||||||
where p = bounds arr
|
where borders = bounds arr
|
||||||
low = fst p
|
low = fst borders
|
||||||
high = snd p
|
high = snd borders
|
||||||
|
|
||||||
-- Usage
|
-- Usage
|
||||||
-- let arr = array (0, 4) [(i, i*i) | i <- [0..4]]
|
-- let arr = array (0, 4) [(i, i*i) | i <- [0..4]] // [(0,0),(1,1),(2,4),(3,9),(4,16)]
|
||||||
-- find 4 arr
|
-- find 4 arr // Just 2
|
||||||
|
-- find 25 arr // Nothing
|
||||||
Reference in New Issue
Block a user