1

Here is my implementation:

mergesort :: (Ord a) => [a] -> [a]
mergesort list = merge (mergesort (left list)) (mergesort (right list))
  where
    left xs = take (div (length xs) 2) xs
    right xs = drop (div (length xs) 2) xs
    merge [] ys = ys
    merge xs [] = xs
    merge (x:xs) (y:ys)
      | x <= y = x : merge xs (y:ys)
      | otherwise = y : merge (x:xs) ys

The code compiles but when I run it my machine crashes. What am I doing wrong?

2
  • Did your original code include the empty case? If not, please rollback that edit. and let Alec know so that he can remove references to that case in his answer. Commented Jun 30, 2016 at 9:52
  • shouldve marked the answer correct. Sorry! Commented Jul 5, 2016 at 21:20

1 Answer 1

2

You are missing base cases - so you get infinite recursion. Trying stepping through your example with lists like [] or [1] and you'll fall straight into the problem.

mergesort :: (Ord a) => [a] -> [a]
mergesort [] = []   -- < ADDED
mergesort [x] = [x] -- < ADDED
mergesort list = merge (mergesort (left list)) (mergesort (right list))
  where
    left xs = take (div (length xs) 2) xs
    right xs = drop (div (length xs) 2) xs
    merge [] ys = ys
    merge xs [] = xs
    merge (x:xs) (y:ys)
      | x <= y = x : merge xs (y:ys)
      | otherwise = y : merge (x:xs) ys
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.