-
Notifications
You must be signed in to change notification settings - Fork 0
/
strand_sort.sf
44 lines (39 loc) · 878 Bytes
/
strand_sort.sf
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
#!/usr/bin/ruby
#
## https://rosettacode.org/wiki/Sorting_algorithms/Strand_sort
#
func merge(x, y) {
var out = [];
while (x && y) {
given (x[-1] <=> y[-1]) {
when ( 1) { out.prepend(x.pop) }
when (-1) { out.prepend(y.pop) }
default { out.prepend(x.pop, y.pop) }
}
}
x + y + out;
}
func strand(x) {
x || return [];
var out = [x.shift];
if (x.len) {
range(-x.len, -1).each { |i|
if (x[i] >= out[-1]) {
out.append(x.pop_at(i));
}
}
}
return out;
}
func strand_sort(x) {
var out = [];
while (var strd = strand(x)) {
out = merge(out, strd);
}
return out;
}
var numbers = [7,6,5,9,8,4,3,1,2,0];
say strand_sort(numbers);
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"];
say strand_sort(strs);