Movatterモバイル変換


[0]ホーム

URL:


Open In App

Visualizing algorithms makes it easier to understand them by analyzing and comparing the number of operations that took place to compare and swap the elements. 3D visualization of algorithms is less common, for this we will use matplotlib to plot bar graphs and animate them to represent the elements of the array.

Approach :

  1. We will generate an array with random elements.
  2. The algorithm will be called on that array and yield statement will be used instead of return statement for visualization purposes.
  3. We will yield the current states of the array after comparing and swapping. Hence the algorithm will return a generator object.
  4. Matplotlib animation will be used to visualize the comparing and swapping of the array.
  5. We will then plot the graph, which will return an object of Poly3dCollection using which further animation will be done.
python3
# import all the modulesimportmatplotlib.pyplotaspltfrommatplotlib.animationimportFuncAnimationfrommpl_toolkits.mplot3dimportaxes3dimportmatplotlibasmpimportnumpyasnpimportrandom# merge sort function to divide the arraydefmergesort(A,start,end):ifend<=start:returnmid=start+((end-start+1)//2)-1# yield from statement is used to# yield the array from the merge functionyield 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=int(input("enter array size\n"))a=[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=plt.figure()ax=fig.add_subplot(projection='3d')# z values and positions of the barsz=np.zeros(n)dx=np.ones(n)dy=np.ones(n)dz=[iforiinrange(len(a))]# Poly3dCollection returned into variable rectsrects=ax.bar3d(range(len(a)),a,z,dx,dy,dz,color=color_map(data_normalizer(range(n))))# setting and x and y limits equal to the length of the arrayax.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'})# text to plot on the charttext=ax.text2D(0.1,0.95,"",horizontalalignment='center',verticalalignment='center',transform=ax.transAxes,color="#E4365D")iteration=[0]# animation function to be repeatedly calleddefanimate(A,rects,iteration):# to clear the bars from the Poly3DCollection objectax.collections.clear()ax.bar3d(range(len(a)),A,z,dx,dy,dz,color=color_map(data_normalizer(range(n))))iteration[0]+=1text.set_text("iterations :{}".format(iteration[0]))# animate function is called here and the generator object is passedanim=FuncAnimation(fig,func=animate,fargs=(rects,iteration),frames=generator,interval=50,repeat=False)plt.show()showGraph()

Output : 
 

For array size 20


 


 


Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp