-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20thSept_Sorting1
64 lines (42 loc) · 1.46 KB
/
20thSept_Sorting1
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
// A list xs from a given Universe X, and a total order on X
// A permutation of xs such that each element is greater than or
// equal to the previous one wrt each other
// comparisons only
// wishful thinking
// imagine we can sort lists with m elements, where m < n
// m can be n - 1
// or m = n/2
// using n-1
// insert the head in the right place, and sort the tail through wishful thinking
// insertion sort for approach A : n-1
function insert(x, xs) {
return is_null(xs) // null, return x as it is
? list(x)
: x <= head(xs) // less than head
? pair(x, xs) // include before the list
: pair(head(xs), insert(x, tail(xs))); // include first element of head(xs) since it is greater than x and then again check for tail
}
function insertion_sort(xs) { // wishful thinking, using insert function to check head and repeating for tail
return is_null(xs)
? xs
: insert(head(xs), insertion_sort(tail(xs)));
}
// order of growth in time: is it n^2?
// selection sort for approach A : n - 1
// find the smallest element x
// remove from the list
// sort the remaining list
// put x in front
function smallest(xs) {
return accumulate((x, y) => x < y ? x : y,
head(xs), tail(xs));
}
function selection_sort(xs) {
if (is_null(xs)) {
return xs;
} else {
const x = smallest(xs);
return pair(x, selection_sort(remove(x, xs)));
}
}
// order of growth of time?