Created
November 25, 2012 17:27
-
-
Save m2ym/4144444 to your computer and use it in GitHub Desktop.
Binominal Heap in Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module BinHeap ( | |
| Heap, | |
| empty, | |
| insert, | |
| findMin, | |
| deleteMin, | |
| fromList, | |
| toList | |
| ) where | |
| import Data.List (minimumBy, unfoldr) | |
| import Data.Function (on) | |
| data Tree a = Tree { label :: a, heap :: Heap a } deriving Show | |
| type Heap a = [(Int, Tree a)] | |
| mergeTree :: Ord a => Int -> Tree a -> Tree a -> Tree a | |
| mergeTree r t@(Tree x xs) s@(Tree y ys) | |
| | x < y = Tree x ((r, s):xs) | |
| | otherwise = Tree y ((r, t):ys) | |
| insertTree :: Ord a => Int -> Tree a -> Heap a -> Heap a | |
| insertTree r t [] = [(r, t)] | |
| insertTree r t (x@(r', t'):xs) | |
| | r < r' = (r, t):x:xs | |
| | r == r' = insertTree (r+1) (mergeTree r t t') xs | |
| | r > r' = x:insertTree r t xs | |
| empty :: Heap a | |
| empty = [] | |
| insert :: Ord a => a -> Heap a -> Heap a | |
| insert x h = insertTree 0 (Tree x []) h | |
| findMin :: Ord a => Heap a -> Maybe a | |
| findMin [] = Nothing | |
| findMin h = Just . minimum $ map (label . snd) h | |
| deleteMin :: Ord a => Heap a -> Maybe (a, Heap a) | |
| deleteMin [] = Nothing | |
| deleteMin h = Just (x, h''') | |
| where | |
| (r, Tree x h') = minimumBy (compare `on` (label . snd)) h | |
| h'' = filter ((r/=) . fst) h | |
| h''' = foldr (uncurry insertTree) h'' h' | |
| fromList :: Ord a => [a] -> Heap a | |
| fromList = foldr insert empty | |
| toList :: Ord a => Heap a -> [a] | |
| toList = unfoldr deleteMin |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import qualified BinHeap as H | |
| heapSort :: Ord a => [a] -> [a] | |
| heapSort = H.toList . H.fromList | |
| main :: IO () | |
| main = print $ heapSort [8, 2, 3, 1, 6, 5, 9, 4, 0, 7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment