Skip to content

Commit b515434

Browse files
aliaksandr-segonSchiele
authored andcommitted
Fix haskell binarysearch (egonSchiele#51)
1 parent 1fa164c commit b515434

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

01_introduction_to_algorithms/Haskell/01_binarysearch.hs

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,20 @@ import Data.Array
33
binarysearch :: Integer -> Array Integer Integer -> Integer -> Integer -> Maybe Integer
44
binarysearch x arr low high
55
| low > high = Nothing
6-
| mid > x = binarysearch x arr low (high - 1)
7-
| mid < x = binarysearch x arr (low + 1) high
6+
| guess > x = binarysearch x arr low (mid - 1)
7+
| guess < x = binarysearch x arr (mid + 1) high
88
| otherwise = Just mid
99
where
10-
mid = arr ! ((low + high) `div` 2)
11-
10+
mid = ((low + high) `div` 2)
11+
guess = arr ! mid
1212

1313
find :: Integer -> Array Integer Integer -> Maybe Integer
1414
find x arr = binarysearch x arr low high
15-
where p = bounds arr
16-
low = fst p
17-
high = snd p
15+
where borders = bounds arr
16+
low = fst borders
17+
high = snd borders
1818

1919
-- Usage
20-
-- let arr = array (0, 4) [(i, i*i) | i <- [0..4]]
21-
-- find 4 arr
20+
-- let arr = array (0, 4) [(i, i*i) | i <- [0..4]] // [(0,0),(1,1),(2,4),(3,9),(4,16)]
21+
-- find 4 arr // Just 2
22+
-- find 25 arr // Nothing

0 commit comments

Comments
 (0)