-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingAlgorithms.hs
More file actions
65 lines (48 loc) · 1.71 KB
/
Copy pathSortingAlgorithms.hs
File metadata and controls
65 lines (48 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
-- Sort by Insertion
--insert an element in a sorted list and keeping it sorted
insert :: (Ord a) => a->[a]->[a]
insert el [] = [el]
insert el (x:xs) | el<=x = el:(x:xs)
| otherwise = x:(insert el xs)
insertionSort::(Ord a) => [a] -> [a]
insertionSort [] = []
insertionSort (x:xs) = insert x (insertionSort xs)
--Quick Sort
qSort :: (Ord a) => [a] -> [a]
qSort [] = []
qSort [x] = [x]
qSort (x:xs) = (qSort inf) ++ [x] ++ (qSort sup)
where
inf = [ y | y <- xs, y <= x ]
sup = [ y | y <- xs, y > x ]
--Sort by selection
--We gonna need a Minimum function to calculate the minimum of a list
minimum' :: (Ord a) => [a] -> a
minimum' [] = error"Empty List"
minimum' [x] = x
minimum' (x:xs) = min x (minimum' xs)
-- we gonna need a function delete' to delete the list's minimum
delete':: (Eq a) => a->[a]->[a]
delete' _ [] = []
delete' el (x:xs) | el == x = xs
|otherwise = x:delete' el xs
selectionSort :: (Ord a) => [a]->[a]
selectionSort [] = []
selectionSort xs = y : selectionSort xs'
where y = minimum xs
xs' = delete' y xs
-- Sort by Fusion
--we will use a function 'halve' to split a list into two equal lists
halve :: [a] -> ([a], [a])
halve xs = splitAt ((length xs)`div`2) xs
-- we will use a function 'fusion' to merge two sorted lists
fusion :: (Ord a) => [a] -> [a] -> [a]
fusion [] ys = ys
fusion xs [] = xs
fusion l1@(x:xs) l2@(y:ys) | x<=y = x: (fusion xs l2)
| otherwise = y:(fusion l1 ys)
fusionSort :: (Ord a) => [a] ->[a]
fusionSort [] = []
fusionSort [x] = [x]
fusionSort xs = fusion (fusionSort l) (fusionSort r)
where (l,r) = halve xs