Your insert
function is slow. Here's how to do insertion sort:
insertionSort :: Ord a => [a] -> [a]
insertionSort xs = f [] xs
where
f rs [] = rs
f rs (x:xs) = f (insert x rs) xs
insert x [] = [x]
insert x rrs@(r:rs) = if x < r then x:rrs else r:insert x rs
In case of confusion, the rrs@(r:rs)
syntax means that rrs
is the entire list, r
is its head, and rs
is its tail.
insert
goes through the list and puts out all the elements that are supposed to be in front of x
, then it puts out x
followed by elements that are supposed to be after x
.