-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort.echo
More file actions
99 lines (86 loc) · 1.57 KB
/
Copy pathsort.echo
File metadata and controls
99 lines (86 loc) · 1.57 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
; Bubble sort and insertion sort — in-place on lists.
; Run: xo run examples/algos/sort.echo
/ std/io
/ std/str
/ std/list
/ std/test
$ swap = (xs, i, j) {
$ t = xs[i]
~ xs[i] = xs[j]
~ xs[j] = t
^ xs
}
$ bubble_sort = (xs) {
$ n = list.len(xs)
~ i = 0
* i < n {
~ j = 0
* j < n - 1 - i {
? xs[j] > xs[j + 1] {
swap(xs, j, j + 1)
}
~ j = j + 1
}
~ i = i + 1
}
^ xs
}
$ insertion_sort = (xs) {
$ n = list.len(xs)
~ i = 1
* i < n {
$ key = xs[i]
~ j = i
* j > 0 && xs[j - 1] > key {
~ xs[j] = xs[j - 1]
~ j = j - 1
}
~ xs[j] = key
~ i = i + 1
}
^ xs
}
$ print_list = (xs) {
* item : xs {
io.print(str.from_int(item))
}
^
}
~ a = [5, 1, 4, 2, 8]
$ sorted_a = bubble_sort(a)
print_list(sorted_a)
~ b = [9, 3, 7, 1, 4, 6, 2]
$ sorted_b = insertion_sort(b)
print_list(sorted_b)
~ c = [1]
print_list(bubble_sort(c))
~ d = [3, 3, 1, 2, 1]
print_list(insertion_sort(d))
test.bench("insertion_sort_100", () {
~ xs = []
~ i = 100
* i > 0 {
~ i = i - 1
~ xs[] = i
}
$ zs = insertion_sort(xs)
})
test.bench("insertion_sort_1k", () {
~ xs = []
~ i = 1000
* i > 0 {
~ i = i - 1
~ xs[] = i
}
$ zs = insertion_sort(xs)
})
test.bench("bubble_sort_100", () {
~ xs = []
~ i = 100
* i > 0 {
~ i = i - 1
~ xs[] = i
}
$ zs = bubble_sort(xs)
})
\ bubble_sort, insertion_sort, swap