-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
62 lines (56 loc) · 1.32 KB
/
script.js
File metadata and controls
62 lines (56 loc) · 1.32 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
let container = document.getElementById("container");
let sortButton = document.getElementById("sort");
let arr = [];
let timeout;
let total = (navigator.userAgent.match(/Mobi/) ? 15 : 30);
random();
function random() {
clearTimeout(timeout);
sortButton.disabled = false;
container.innerHTML = "";
for (let i = 0; i < total; i++) {
arr[i] = Math.floor(Math.random() * 95) + 1;
show();
}
}
function sort() {
sortButton.disabled = true;
let copy = [...arr];
const swaps = bubbleSort(copy);
play(swaps);
}
function play(swaps) {
if (swaps.length == 0) {
return;
}
const [i, j] = swaps.shift();
[arr[i], arr[j]] = [arr[j], arr[i]];
show();
timeout = setTimeout(() => {
play(swaps);
}, 130);
}
function bubbleSort(arr) {
const swaps = [];
let temp;
for (let i = 0; i < total; i++) {
for (let j = 0; j < total; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swaps.push([j, j + 1]);
}
}
}
return swaps;
}
function show() {
container.innerHTML = "";
for (let i = 0; i < total; i++) {
let div = document.createElement("div");
div.style.height = `${arr[i]}%`;
div.classList.add("bar");
container.appendChild(div);
}
}