From b515434b3f4686c315f8c12e599a5e88a68ee114 Mon Sep 17 00:00:00 2001 From: Aliaksandr Date: Sat, 3 Feb 2018 22:56:41 +0300 Subject: [PATCH] Fix haskell binarysearch (#51) --- .../Haskell/01_binarysearch.hs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/01_introduction_to_algorithms/Haskell/01_binarysearch.hs b/01_introduction_to_algorithms/Haskell/01_binarysearch.hs index 923f209..3a4f0c5 100644 --- a/01_introduction_to_algorithms/Haskell/01_binarysearch.hs +++ b/01_introduction_to_algorithms/Haskell/01_binarysearch.hs @@ -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 \ No newline at end of file +-- 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 \ No newline at end of file