Haskell @ Club De Science - Sorting



> module InsertSort where

Insert Sort

Wiki Insert Sort

How to implement insertSort in Haskell

Step 1: Implement insert

insert x xs inserts the element x into the sorted list xs

> insert :: (Ord a) => a -> [a] -> [a]
> insert x []     = [x]
> insert x (y:ys) | x > y  = y:insert x ys 
>                 | y >= x = x:y:ys 
> 
> 
> sort :: (Ord a) => [a] -> [a]
> sort xs = foldr (insert) [] xs

Step 2: Use insert to implement sorting

Use insert to compine the elements of the initial unsorted list

sort [5, 4, 2, 3, 10] insert 5 $ sort [4, 2, 3, 10] insert 5 $ insert 4 $ sort [2, 3, 10] insert 5 $ insert 4 $ insert 2 $ sort [3, 10] insert 5 $ insert 4 $ insert 2 $ insert 3 $ sort [10] insert 5 $ insert 4 $ insert 2 $ insert 3 $ insert 10 [] insert 5 $ insert 4 $ insert 2 $ insert 3 $ [10] insert 5 $ insert 4 $ insert 2 $ [3, 10] insert 5 $ insert 4 $ [2, 3, 10] insert 5 $ [2, 3, 4, 10][2, 3, 4, 5, 10]

Reminder: Did you user fold?

When you want to combine list elements, with a function and a base case, it is suggested to use folds:

foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)

How to implement a function in Haskell

OR

QuickSort

Wiki QuickSort

I put the pivot in the middle, the (sorted list of) elements that are less or equal than the pivot at the left, and the (sorted list of) elements that are greater that the pivot at the left:

> quicksort' []     = []
> quicksort' (x:xs) = quicksort' [y | y<-xs, y<x] ++ [x] ++ quicksort' [y | y <- xs, y >=x]

How do I get the elements of xs that are less than x?

leq_than_x = filter (\y -> y <= x) xs

where (\y -> y <= x) is an anonymous function with argument y and body y <= x that behaves exactly like f:

f y = y <= x

OR

[y | y <- xs, y <= x]
> quicksort'' (x:xs) = leq_than_x ++ [x] ++ g_than_x
>   where leq_than_x = quicksort [y | y <- xs, y <= x]
>         g_than_x   = quicksort [y | y <- xs, y > x]

Finally putting everything in one line:

> quicksort []     = []
> quicksort (x:xs) = (quicksort [y | y <- xs, y <= x]) ++ [x] ++ (quicksort [y | y <- xs, y > x])

In Haskell you CAN implement quicksort in one line! Compare it with implementations in any other language…. Isn’t this one more intuitive?