Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132930 views
License: OTHER
1
module Sort where
2
3
-- Aufgabe 2
4
-- insert list el: sorts an elmenet el into a sorted list
5
insert :: (Ord t) => [t] -> t -> [t]
6
insert [] x = [x]
7
insert [a] x
8
| x < a = [x, a]
9
| otherwise = [a, x]
10
insert (a:b:qs) x
11
| x < a = [x,a,b] ++ qs
12
| x < b = [a,x,b] ++ qs
13
| otherwise = [a,b] ++ insert qs x
14
15
-- sortH q r: Sorts an unsorted list r into a sorted list q
16
insertH :: (Ord t) => [t] -> [t] -> [t]
17
insertH q [] = q
18
insertH q [r] = insert q r
19
insertH q (r:rest) = insertH (insert q r) rest
20
21
-- insertSort list: sorts list
22
insertSort :: (Ord t) => [t] -> [t]
23
insertSort [] = []
24
insertSort [a] = [a]
25
insertSort (a:qs) = insertH [a] qs
26
27
-- Aufgabe 3
28
merge :: (Ord t) => [t] -> [t] -> [t]
29
merge [] x = x
30
merge x [] = x
31
merge (x:xs) (y:ys)
32
| x <= y = x : merge xs (y:ys)
33
| otherwise = y : merge ys (x:xs)
34
35
mergeSort :: (Ord t) => [t] -> [t]
36
mergeSort [] = []
37
mergeSort [x] = [x]
38
mergeSort xs = merge (mergeSort top) (mergeSort bottom) where
39
(top, bottom) = splitAt (div (length xs) 2) xs
40
41
-- Aufgabe 4
42
-- Teste
43
isSorted :: (Ord t) => [t] -> Bool
44
isSorted [] = True
45
isSorted [a] = True
46
isSorted (a:b:xs)
47
| (a <= b) && isSorted xs = True
48
| otherwise = False
49
50
insertSortedIsSorted :: (Ord t) => [t] -> Bool
51
insertSortedIsSorted xs = isSorted(insertSort xs)
52
53
mergeSortedIsSorted :: (Ord t) => [t] -> Bool
54
mergeSortedIsSorted xs = isSorted(mergeSort xs)
55
56