1+ const n = 20
2+ const array = [ ] ;
3+
4+ init ( ) ;
5+
6+ let audioCtx = null ;
7+
8+ function playNote ( freq ) {
9+ if ( audioCtx == null ) {
10+ audioCtx = new (
11+ AudioContext ||
12+ webkitAudioContext ||
13+ window . webkitAudioContext
14+ ) ( ) ;
15+ }
16+ const dur = 0.1 ;
17+ const osc = audioCtx . createOscillator ( ) ;
18+ osc . frequency . value = freq ;
19+ osc . start ( ) ;
20+ osc . stop ( audioCtx . currentTime + dur ) ;
21+ const node = audioCtx . createGain ( ) ;
22+ node . gain . value = 0.1 ;
23+ node . gain . linearRampToValueAtTime (
24+ 0 , audioCtx . currentTime + dur
25+ ) ;
26+ osc . connect ( node ) ;
27+ node . connect ( audioCtx . destination ) ;
28+ }
29+
30+
31+ function init ( ) {
32+ for ( let i = 0 ; i < n ; i ++ ) {
33+ array [ i ] = Math . random ( ) ;
34+ }
35+ showBars ( ) ;
36+ }
37+
38+ function play ( ) {
39+ const copy = [ ...array ] ;
40+ const moves = bubbleSort ( copy ) ;
41+ animate ( moves ) ;
42+ }
43+
44+ function animate ( moves ) {
45+ if ( moves . length == 0 ) {
46+ showBars ( ) ;
47+ return ;
48+ }
49+ const move = moves . shift ( ) ;
50+ const [ i , j ] = move . indices ;
51+
52+ if ( move . type == "swap" ) {
53+ [ array [ i ] , array [ j ] ] = [ array [ j ] , array [ i ] ] ;
54+ }
55+
56+ playNote ( 250 + array [ i ] * 500 ) ;
57+ playNote ( 300 + array [ j ] * 500 ) ;
58+
59+ showBars ( move ) ;
60+ setTimeout ( function ( ) {
61+ animate ( moves ) ;
62+ } , 75 ) ;
63+ }
64+
65+ function bubbleSort ( array ) {
66+ const moves = [ ]
67+ do {
68+ var swapped = false ;
69+ for ( let i = 1 ; i < array . length ; i ++ ) {
70+ // moves.push({indices:[i-1,i],type:"comp"});
71+ if ( array [ i - 1 ] > array [ i ] ) {
72+ swapped = true ;
73+ moves . push ( { indices :[ i - 1 , i ] , type :"swap" } ) ;
74+ [ array [ i - 1 ] , array [ i ] ] = [ array [ i ] , array [ i - 1 ] ] ;
75+ }
76+ }
77+ } while ( swapped ) ;
78+ return moves ;
79+ }
80+
81+ function showBars ( move ) {
82+ container . innerHTML = "" ;
83+ for ( let i = 0 ; i < array . length ; i ++ ) {
84+ const bar = document . createElement ( "div" ) ;
85+ bar . style . height = array [ i ] * 100 + "%" ;
86+ bar . classList . add ( "bar" ) ;
87+
88+ if ( move && move . indices . includes ( i ) ) {
89+ bar . style . backgroundColor =
90+ move . type == "swap" ?"purple" :"blue" ;
91+ }
92+ container . appendChild ( bar ) ;
93+ }
94+ }
0 commit comments