1- var data = [ 23 , 15 , 16 , 8 , 5 , 4 , 19 , 22 ] ;
2- var svg , bandScale ;
1+ var data , svg , bandScale , text ;
2+ data = [ ] ;
3+ for ( var i = 0 ; i < 15 ; i ++ ) {
4+ data . push ( Math . floor ( Math . random ( ) * 100 ) + 1 ) ;
5+ }
36createChart ( ) ;
47
58function createChart ( ) {
@@ -35,11 +38,38 @@ function createChart() {
3538 . attr ( "height" , function ( d ) {
3639 return heightScale ( d ) ;
3740 } )
38- . style ( "fill" , "steelblue" ) ;
41+ . style ( "fill" , "rgb(173, 216, 230)" ) ;
42+
43+ svg
44+ . selectAll ( "text" )
45+ . data ( data )
46+ . enter ( )
47+ . append ( "text" )
48+ . text ( function ( d ) {
49+ return d ;
50+ } )
51+ . attr ( "x" , function ( d , i ) {
52+ return bandScale ( d ) + 5 ;
53+ } )
54+ . attr ( "y" , function ( d ) {
55+ var val = h - heightScale ( d ) ;
56+ console . log ( val ) ;
57+ if ( val > 20 ) {
58+ return val ;
59+ } else {
60+ return 50 ;
61+ }
62+ } )
63+ . style ( "width" , bandScale . bandwidth )
64+ . style ( "fill" , "black" )
65+ . style ( "font-size" , w / data . length / 3 )
66+ . style ( "font-family" , "sans-serif" )
67+ . style ( "z-index" , 1 ) ;
3968}
69+
4070document . getElementById ( "random-data" ) . addEventListener ( "click" , function ( ) {
4171 data = [ ] ;
42- for ( var i = 0 ; i < 20 ; i ++ ) {
72+ for ( var i = 0 ; i < 15 ; i ++ ) {
4373 data . push ( Math . floor ( Math . random ( ) * 100 ) + 1 ) ;
4474 }
4575 console . log ( data ) ;
@@ -63,23 +93,13 @@ function selectionSort() {
6393 temp = data [ i ] ;
6494 data [ i ] = smallest ;
6595 data [ pos ] = temp ;
66- var dOrder = data . map ( function ( d ) {
67- return d ;
68- } ) ;
69- bandScale . domain ( dOrder ) ;
70- svg
71- . transition ( )
72- . duration ( 750 )
73- . selectAll ( "rect" )
74- . attr ( "x" , function ( d ) {
75- return bandScale ( d ) ;
76- } ) ;
96+
7797 var swooshAudio = new Audio (
7898 "/algorithm-visualizer/sound-effects/swoosh.mp3"
7999 ) ;
80100 swooshAudio . play ( ) ;
81101 }
82-
102+ sortAnimate ( data ) ;
83103 await timer ( 1000 ) ; // then the created Promise can be awaited
84104 }
85105 svg . selectAll ( "rect" ) . style ( "fill" , "green" ) ;
@@ -94,3 +114,24 @@ function selectionSort() {
94114document
95115 . getElementById ( "selection-sort" )
96116 . addEventListener ( "click" , selectionSort ) ;
117+
118+ function sortAnimate ( data ) {
119+ var dOrder = data . map ( function ( d ) {
120+ return d ;
121+ } ) ;
122+ bandScale . domain ( dOrder ) ;
123+ svg
124+ . transition ( )
125+ . duration ( 750 )
126+ . selectAll ( "rect" )
127+ . attr ( "x" , function ( d ) {
128+ return bandScale ( d ) ;
129+ } ) ;
130+ svg
131+ . transition ( )
132+ . duration ( 750 )
133+ . selectAll ( "text" )
134+ . attr ( "x" , function ( d ) {
135+ return bandScale ( d ) + 5 ;
136+ } ) ;
137+ }
0 commit comments