-
Notifications
You must be signed in to change notification settings - Fork 1
/
script.js
61 lines (51 loc) · 1.04 KB
/
script.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
const n = 40
const array = []
init();
function init(){
for(let i =0; i<n; i++){
array[i] = Math.random();
}
showbars();
}
function play()
{
const copy = [...array];
const swaps = bubblesort(copy);
animate(swaps);
showbars();
}
function animate(swaps){
if(swaps.length == 0){
return;
}
const [i,j] = swaps.shift();
[array[i],array[j]] = [array[j], array[i]];
showbars();
setTimeout(function(){
animate(swaps);
}, 8);
}
function bubblesort(array){
const swaps = [];
do{
var swapped = false;
for(let i =1; i<array.length; ++i){
if(array[i-1]>array[i]){
swapped = true;
swaps.push([i-1,i]);
[array[i-1],array[i]]=[array[i],array[i-1]];
}
}
}while(swapped);
return swaps;
}
function showbars(){
container.innerHTML = "";
for(let i =0; i<array.length; ++i)
{
const bar=document.createElement("div");
bar.style.height=array[i]*100+"%";
bar.classList.add("bar");
container.appendChild(bar);
}
}