# import all the modulesimportmatplotlib.pyplotaspltfrommatplotlib.animationimportFuncAnimationfrommpl_toolkits.mplot3dimportaxes3dimportmatplotlibasmpimportnumpyasnpimportrandom# function to recursively divide the arradefmergesort(A,start,end):ifend<=start:returnmid=start+((end-start+1)//2)-1# yield from statements have been used to yield# the array from the functionsyield frommergesort(A,start,mid)yield frommergesort(A,mid+1,end)yield frommerge(A,start,mid,end)# function to merge the arraydefmerge(A,start,mid,end):merged=[]leftIdx=startrightIdx=mid+1whileleftIdx<=midandrightIdx<=end:ifA[leftIdx]<A[rightIdx]:merged.append(A[leftIdx])leftIdx+=1else:merged.append(A[rightIdx])rightIdx+=1whileleftIdx<=mid:merged.append(A[leftIdx])leftIdx+=1whilerightIdx<=end:merged.append(A[rightIdx])rightIdx+=1foriinrange(len(merged)):A[start+i]=merged[i]yieldA# function to plot barsdefshowGraph():# for random unique valuesn=20a=[iforiinrange(1,n+1)]random.shuffle(a)datasetName='Random'# generator object returned by the functiongenerator=mergesort(a,0,len(a)-1)algoName='Merge Sort'# style of the chartplt.style.use('fivethirtyeight')# set colors of the barsdata_normalizer=mp.colors.Normalize()color_map=mp.colors.LinearSegmentedColormap("my_map",{"red":[(0,1.0,1.0),(1.0,.5,.5)],"green":[(0,0.5,0.5),(1.0,0,0)],"blue":[(0,0.50,0.5),(1.0,0,0)]})fig,ax=plt.subplots()# bar containerbar_rects=ax.bar(range(len(a)),a,align="edge",color=color_map(data_normalizer(range(n))))# setting the limits of x and y axesax.set_xlim(0,len(a))ax.set_ylim(0,int(1.1*len(a)))ax.set_title("ALGORITHM : "+algoName+"\n"+"DATA SET : "+datasetName,fontdict={'fontsize':13,'fontweight':'medium','color':'#E4365D'})# the text to be shown on the upper left# indicating the number of iterations# transform indicates the position with# relevance to the axes coordinates.text=ax.text(0.01,0.95,"",transform=ax.transAxes,color="#E4365D")iteration=[0]defanimate(A,rects,iteration):forrect,valinzip(rects,A):# setting the size of each bar equal# to the value of the elementsrect.set_height(val)iteration[0]+=1text.set_text("iterations :{}".format(iteration[0]))# call animate function repeatedlyanim=FuncAnimation(fig,func=animate,fargs=(bar_rects,iteration),frames=generator,interval=50,repeat=False)plt.show()showGraph()