Adding Haskell examples (#17)
* Adding binary search example for Haskell * Adding selection sort example in Haskell * Adding Haskell examples for chapter 3 * Adding examples for chapter 4 * Adding examples for chapter 5 * Adding git ignore * Add Haskell example for BFS
This commit is contained in:
committed by
Aditya Bhargava
parent
c5c2563d05
commit
6f78bdf3d7
21
01_introduction_to_algorithms/Haskell/01_binarysearch.hs
Normal file
21
01_introduction_to_algorithms/Haskell/01_binarysearch.hs
Normal file
@@ -0,0 +1,21 @@
|
||||
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
|
||||
| otherwise = Just mid
|
||||
where
|
||||
mid = arr ! ((low + high) `div` 2)
|
||||
|
||||
|
||||
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
|
||||
|
||||
-- Usage
|
||||
-- let arr = array (0, 4) [(i, i*i) | i <- [0..4]]
|
||||
-- find 4 arr
|
||||
Reference in New Issue
Block a user