-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
93 lines (81 loc) · 2 KB
/
script.js
File metadata and controls
93 lines (81 loc) · 2 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
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
const n=20;
const array=[];
init();
let audioCtx=null;
function playNote(freq){
if(audioCtx==null){
audioCtx=new(
AudioContext ||
webkitAudioContext ||
window.webkitAudioContext
)();
}
const dur=0.1;
const osc=audioCtx.createOscillator();
osc.frequency.value=freq;
osc.start();
osc.stop(audioCtx.currentTime+dur);
const node=audioCtx.createGain();
node.gain.value=0.1;
node.gain.linearRampToValueAtTime(
0, audioCtx.currentTime+dur
);
osc.connect(node);
node.connect(audioCtx.destination);
}
function init(){
for(let i=0;i<n;i++){
array[i]=Math.random();
}
showBars();
}
function play(){
const copy=[...array];
const moves=bubbleSort(copy);
animate(moves);
}
function animate(moves){
if(moves.length==0){
showBars();
return;
}
const move=moves.shift();
const [i,j]=move.indices;
if(move.type=="swap"){
[array[i],array[j]]=[array[j],array[i]];
}
playNote(200+array[i]*500);
playNote(200+array[j]*500);
showBars(move);
setTimeout(function(){
animate(moves);
},50);
}
function bubbleSort(array){
const moves=[];
do{
var swapped=false;
for(let i=1;i<array.length;i++){
//moves.push({indices:[i-1,i],type:"comp"});
if(array[i-1]>array[i]){
swapped=true;
moves.push({indices:[i-1,i],type:"swap"});
[array[i-1],array[i]]=[array[i],array[i-1]];
}
}
}while(swapped);
return moves;
}
function showBars(move){
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");
if(move && move.indices.includes(i)){
bar.style.backgroundColor=
move.type=="swap"?"rgb(13, 213, 240)":"rgb(255, 0, 21)";
}
container.appendChild(bar);
}
}