Skip to content
Related Articles
Visualizing Bubble sort using Python
• Last Updated : 11 Oct, 2020

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

 `# 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:``            ``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)``     ` `    ``# 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 ``=` `ax.bar(``range``(``len``(A)), 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):``            ``rect.set_height(val)``        ``iteration[``0``] ``+``=` `1``        ``text.set_text(f``"# of operations: {iteration}"``)`` ` `    ``# creating animation object for rendering the iteration``    ``anim ``=` `animation.FuncAnimation(``        ``fig,``        ``func``=``update,``        ``fargs``=``(bar_sub, iteration),``        ``frames``=``generator,``        ``repeat``=``True``,``        ``blit``=``False``,``        ``interval``=``15``,``        ``save_count``=``90000``,``    ``)``     ` `    ``# for showing the animation on screen``    ``plt.show()``    ``plt.close()`` ` ` ` `if` `__name__ ``=``=` `"__main__"``:``    ``visualize()`

Output:

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up