1
- const n = 25 ;
1
+ const n = 50 ;
2
2
const array = [ ] ;
3
3
init ( ) ;
4
4
5
- let audioCtx = null ;
6
-
7
- function playNote ( freq ) {
8
- if ( audioCtx == null ) {
9
- audioCtx = new (
10
- AudioContext ||
11
- webkitAudioContext ||
12
- window . webkitAudioContext
13
- ) ( ) ;
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
- function init ( ) {
31
- for ( i = 0 ; i < n ; i ++ ) {
32
- array [ i ] = Math . random ( ) ;
33
- }
34
- showBars ( ) ;
35
- }
36
-
37
- function play ( ) {
38
- const copyArray = [ ...array ] ;
39
- const moves = bubbleSort ( copyArray ) ;
40
- animate ( moves ) ;
41
- }
42
-
43
- function animate ( moves ) {
44
- if ( moves . length == 0 ) { return ; }
45
-
46
- const move = moves . shift ( ) ; //i and j contains i-1 and i.
47
- const [ i , j ] = move . indices ;
48
- if ( move . type == "swap" ) {
49
- [ array [ i ] , array [ j ] ] = [ array [ j ] , array [ i ] ] ;
50
- }
51
-
52
- playNote ( 200 + array [ i ] * 500 ) ; //linear interpolation function.
53
- playNote ( 200 + array [ j ] * 500 ) ;
54
- showBars ( move ) ;
55
- setTimeout ( function ( ) {
56
- animate ( moves ) ;
57
- } , 50 ) ;
58
- }
59
-
60
-
61
-
62
5
function showBars ( move ) {
63
6
64
7
container . innerHTML = "" ;
@@ -75,4 +18,17 @@ function showBars(move){
75
18
}
76
19
container . appendChild ( bar ) ;
77
20
}
21
+ } ;
22
+
23
+ function init ( ) {
24
+ for ( i = 0 ; i < n ; i ++ ) {
25
+ array [ i ] = Math . random ( ) ;
26
+ }
27
+ showBars ( ) ;
28
+ }
29
+
30
+ function play ( ) {
31
+ const copyArray = [ ...array ] ;
32
+ const moves = bubbleSort ( copyArray ) ;
33
+ animate ( moves ) ;
78
34
}
0 commit comments