Prerequisites: Introduction to Matplotlib, Introduction to PyQt5, Bubble Sort
Learning any algorithm can be difficult, and since you are here at GeekforGeeks, you definitely love to understand and implement various algorithms. It is tough for every one of us to understand algorithms at the first go. We tend to understand those things more which are visualized properly. One of the basic problems that we start with is sorting algorithms. It might have been challenging for you to learn those algorithms so here we are today showing you how you can visualize them.
Modules Needed
Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. To install it type the below command in the terminal.
pip install matplotlib
PyQt5: PyQt5 is cross-platform GUI toolkit, a set of python bindings for Qt v5. One can develop an interactive desktop application with so much ease because of the tools and simplicity provided by this library. To install it type the below command in the terminal.
pip install PyQt5==5.9.2
So, with that all set up, let’s get started with the actual coding. First, create a file named main.py and add the following lines of code to it.
Python3
import random
from matplotlib import pyplot as plt, animation
def swap(A, i, j):
A[i], A[j] = A[j], A[i]
def bubblesort(A):
swapped = True
for i in range ( len (A) - 1 ):
if not swapped:
return
swapped = False
for j in range ( len (A) - 1 - i):
if A[j] > A[j + 1 ]:
swap(A, j, j + 1 )
swapped = True
yield A
def visualize():
N = 30
A = list ( range ( 1 , N + 1 ))
random.shuffle(A)
generator = bubblesort(A)
fig, ax = plt.subplots()
ax.set_title( "Bubble Sort O(n\N{SUPERSCRIPT TWO})" )
bar_sub = ax.bar( range ( len (A)), A, align = "edge" )
ax.set_xlim( 0 , N)
text = ax.text( 0.02 , 0.95 , "", transform = ax.transAxes)
iteration = [ 0 ]
def update(A, rects, iteration):
for rect, val in zip (rects, A):
rect.set_height(val)
iteration[ 0 ] + = 1
text.set_text(f "# of operations: {iteration[0]}" )
anim = animation.FuncAnimation(
fig,
func = update,
fargs = (bar_sub, iteration),
frames = generator,
repeat = True ,
blit = False ,
interval = 15 ,
save_count = 90000 ,
)
plt.show()
plt.close()
if __name__ = = "__main__" :
visualize()
|
Output:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Oct, 2020
Like Article
Save Article