1+ import  matplotlib .pyplot  as  plt 
2+ import  matplotlib .animation  as  animation 
3+ from  sorting_algorithms  import  BubbleSort 
4+ import  sys 
5+ import  random 
6+ 
7+ # when this file is itself is ran, not by importing. 
8+ if  __name__  ==  '__main__' :
9+ li  =  []
10+ step_cnt  =  0  
11+ try :
12+ N  =  int (input ("Enter no. of elements to be sorted: " ))
13+ choice  =  int (input ("Choice(1:select randomly, 2:input manually): " ))
14+ if  choice  ==  1 :
15+ li  =  random .sample (range (0 , 2 * N ), N ) #selects N random nums from range(0, 2N) 
16+ elif  choice  ==  2 :
17+ for  i  in  range (N ):
18+ num  =  input ("Enter {}th element: " .format (i + 1 ))
19+ li .append (int (num ))
20+ else :
21+ sys .exit ("Invalid input!" )
22+ 
23+ algo_dict  =  {1 :'Bubble Sort' , 2 :'Merge Sort' }
24+ algo  =  int (input ('Sorting Algorithm{}: ' .format (algo_dict )))
25+ if  algo  ==  1 :
26+ generator_func  =  BubbleSort (li )
27+ else :
28+ sys .exit ("Invalid input!" )
29+ 
30+ except  Exception  as  e :
31+ raise  e 
32+ 
33+ # plot configurations 
34+ fig , ax  =  plt .subplots (num =  'Sorting Algorithm Visualizer' )
35+ ax .set_title (algo_dict [algo ])
36+ plt .xlabel ('Elements being sorted' )
37+ bar_rec  =  ax .bar (range (len (li )), li , tick_label = li ) #container for bar diagram. 
38+ # by using plt.gcf().transFigure, (0,0) is the bottom left and (1,1) is the top right of the figure 
39+ plt .text (0.015 , 0.94 , 'input:{}' .format (str (li )), fontsize = 10 , transform = plt .gcf ().transFigure ) #to show input data 
40+ step_text  =  plt .text (0.015 , 0.90 , "" , fontsize = 10 , transform = plt .gcf ().transFigure ) #to show no. steps 
41+ 
42+ def  update_fig (li ):
43+ global  step_cnt 
44+ for  rect , val  in  zip (bar_rec , li ):
45+ rect .set_height (val )
46+ ax .set_xticklabels (li ) #also changing xticks labels to match with changing bars. 
47+ # to update step count 
48+ step_cnt  +=  1 
49+ step_text .set_text ('No. of steps: {}' .format (step_cnt ))
50+ 
51+ # at each 'frames' it calls 'func' function, which then modifies the plot based on 'li' at that time. 
52+ anim  =  animation .FuncAnimation (fig , func = update_fig , frames = generator_func , interval = 200 , repeat = False )
53+ plt .show ()
54+ 
55+ # In abstract, above animation stuff kinda working like this. 
56+ # for i in QuickSort(li): 
57+ #	for rect, j in zip(bar_rec, li): 
58+ #	rect.set_height(j) 
59+ #	ax.set_xticklabels(li) 
60+ #	fig.canvas.draw() 
61+ #	plt.pause(0.0001) 
62+ # plt.show() 
0 commit comments