Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Haskell mergesort

Name: Anonymous 2012-04-24 5:29

Haskell newbie here, how is my mergesort?


merge :: (Ord a) => [a] -> [a] -> [a]
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys) = if (x < y) then x:(merge xs (y:ys)) else y:(merge (x:xs) ys)

mergeSort :: (Ord a) => [a] -> [a]
mergeSort []  = []
mergeSort [x] = [x]
mergeSort xs  = let mid   = (length xs) `div` 2
                    parts = (splitAt mid xs)
                    left  = mergeSort (fst parts)
                    right = mergeSort (snd parts)
                in merge left right

Name: Anonymous 2012-04-24 21:54

sight*, if you are _that_ concerned about the length, it's only
expensive the first time you call it, after that is only as
expensive as in any other language. you could pass the result
the first time, but that's an extra optimization (but it just a closure away)

OP: is ok as a mergersort. nothing to add.

also don't be afraid to use length in a sorting function, information theory tells us that every element of the data-structure must be compared against every other one, so it obvious that you data-structure needs to be finite, (try sort on [1..])

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List