-
Notifications
You must be signed in to change notification settings - Fork 1
/
merge.js
93 lines (77 loc) · 2.37 KB
/
merge.js
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
"use scrict";
const merge = async function (l, m, r) {
const sz2 = Number(barsEl.childElementCount);
for (let i = 0; i < sz2; ++i)
if (i < l || i > r) barsEl.children[i].style.opacity = "0.5";
const n1 = Number(m - l + 1);
const n2 = Number(r - m);
const L = [];
const R = [];
for (let i = 0; i < n1; i++) L.push(bars[l + i]);
for (let j = 0; j < n2; j++) R.push(bars[m + 1 + j]);
let i = 0,
j = 0,
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
bars[k] = L[i];
barsEl.children[k].style.height = `${L[i] * 0.94}%`;
// barsEl.children[k].children[0].innerText = L[i];
i++;
} else {
bars[k] = R[j];
barsEl.children[k].style.height = `${R[j] * 0.94}%`;
// barsEl.children[k].children[0].innerText = R[j];
j++;
}
k++;
await waitforme(Number(speedSlider.value));
}
while (i < n1) {
bars[k] = L[i];
barsEl.children[k].style.height = `${L[i] * 0.94}%`;
// barsEl.children[k].children[0].innerText = L[i];
i++;
k++;
await waitforme(Number(speedSlider.value));
}
while (j < n2) {
bars[k] = R[j];
barsEl.children[k].style.height = `${R[j] * 0.94}%`;
// barsEl.children[k].children[0].innerText = R[j];
j++;
k++;
await waitforme(Number(speedSlider.value));
}
for (let i = 0; i < sz2; ++i)
if (i < l || i > r) barsEl.children[i].style.opacity = "1.0";
};
const mergeS = async function (l, r) {
if (l >= r) {
return;
}
const m = l + Math.trunc((r - l) / 2);
await mergeS(l, m);
await mergeS(m + 1, r);
await merge(l, m, r);
};
const doGreen = async function (sz) {
for (let i = 0; i < sz; ++i) {
barsEl.children[i].style.backgroundColor = "green";
await waitforme(Number(speedSlider.value));
}
};
const mergeSort = async function () {
document.getElementById("merge").classList.toggle("active-btn");
tempDisable();
const barsEl = document.getElementById("bars");
const sz = Number(barsEl.childElementCount);
await mergeS(0, Number(sz - 1)).then(() => doGreen(sz));
document.getElementById("random-array").classList.remove("disabled");
document.getElementById("reversed-array").classList.remove("disabled");
document.getElementById("sorted-array").classList.remove("disabled");
document.getElementById("size").classList.remove("disabled");
document.getElementById("merge").classList.toggle("active-btn");
};
const btnMergeSort = document.getElementById("merge");
btnMergeSort.addEventListener("click", mergeSort);