-
Notifications
You must be signed in to change notification settings - Fork 0
/
bubblesort_list_studio10
80 lines (58 loc) · 1.58 KB
/
bubblesort_list_studio10
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
function bubblesort_list(L) {
/*
function helper(lst, count){
if(is_null(lst)){
return null;
}
else if(is_null(tail(lst)) || count === 0){
return L;
}
else{
const rest = tail(lst);
if (head(lst) > head(rest)){
const temp = head(lst);
set_head(lst, head(rest));
set_head(rest, temp);
}
return helper(tail(lst), count - 1);
}
}
const len = length(L);
let sorted = L;
for(let i = 0; i < len - 1; i = i + 1){
sorted = helper(sorted, len - i);
display(sorted);
}
*/
const len = length(L);
for(let i = len - 1; i >= 1; i = i - 1){
let sorted = L;
for(let j = 0; j < i; j = j + 1){
const rest = tail(sorted);
if (head(sorted) > head(rest)){
const temp = head(sorted);
set_head(sorted, head(rest));
set_head(rest, temp);
}
sorted = rest;
}
}
}
const LL = list(3, 5, 2, 4, 1);
bubblesort_list(LL);
LL; // should show [1, [2, [3, [4, [5, null]]]]]
// logic
// the head starting from the end
// has to be the largest
// eg: [3,5,2,4,1]
// first we do
// [3,5,2,4,1]
// [3,2,5,4,1]
// [3,2,4,5,1]
// [3,2,4,1,5]
// now 5 is at the end
// next we do for second last element
// [2,3,4,1,5]
// [2,3,4,1,5]
// [2,3,1,4,5]
// and then so on...