Open In App
Related Articles

Visualizing Bubble sort using Python

Improve Article
Save Article
Like Article

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 and add the following lines of code to it.


# imports
import random
from matplotlib import pyplot as plt, animation
# helper methods
def swap(A, i, j):
    A[i], A[j] = A[j], A[i]
# algorithms
def bubblesort(A):
    swapped = True
    for i in range(len(A) - 1):
        if not swapped:
        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))
    # creates a generator object containing all 
    # the states of the array while performing 
    # sorting algorithm
    generator = bubblesort(A)
    # creates a figure and subsequent subplots
    fig, ax = plt.subplots()
    ax.set_title("Bubble Sort O(n\N{SUPERSCRIPT TWO})")
    bar_sub =, A, align="edge")
    # sets the maximum limit for the x-axis
    ax.set_xlim(0, N)
    text = ax.text(0.02, 0.95, "", transform=ax.transAxes)
    iteration = [0]
    # helper function to update each frame in plot
    def update(A, rects, iteration):
        for rect, val in zip(rects, A):
        iteration[0] += 1
        text.set_text(f"# of operations: {iteration[0]}")
    # creating animation object for rendering the iteration
    anim = animation.FuncAnimation(
        fargs=(bar_sub, iteration),
    # for showing the animation on screen
if __name__ == "__main__":


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
Similar Reads
Complete Tutorials