-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathP29040.hs
61 lines (49 loc) · 1.49 KB
/
P29040.hs
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
-- PROBLEM: https://jutge.org/problems/P29040_en
insert :: [Int] -> Int -> [Int]
-- given a sorted list and an element, correctly inserts the new element in the list
insert [] x = [x]
insert (y:ys) x
| x <= y = x : y : ys
| otherwise = y : (insert ys x)
isort :: [Int] -> [Int]
-- implements insertion sort using the previous function
isort [] = []
isort (x:xs) = insert (isort xs) x
remove :: [Int] -> Int -> [Int]
remove [] _ = []
remove (x:xs) n
| x == n = xs
| otherwise = x:(remove xs n)
ssort :: [Int] -> [Int]
-- implements selection sort using the previous function
ssort [] = []
ssort l = x : (ssort (remove l x)) where x = minimum l
merge :: Ord a => [a] -> [a] -> [a]
-- given two sorted lists, merges them to get a list with all the elements in sorted order
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
| x <= y = x : merge xs (y:ys)
| otherwise = y : merge (x:xs) ys
half :: [Int] -> ([Int], [Int])
half l = (take n l, drop n l)
where
n = (div (length l) 2)
msort :: [Int] -> [Int]
msort [] = []
msort [x] = [x]
msort l = merge (msort h1) (msort h2)
where
(h1, h2) = half l
qsort :: [Int] -> [Int]
qsort [] = []
qsort (x:xs) = (qsort lower)++[x]++(qsort higher)
where
lower = [a | a <- xs, a <= x]
higher = [a | a <- xs, a > x]
genQsort :: Ord a => [a] -> [a]
genQsort [] = []
genQsort (x:xs) = (genQsort lower)++[x]++(genQsort higher)
where
lower = [a | a <- xs, a <= x]
higher = [a | a <- xs, a > x]