Sorting algorithms are a fundamental part of computer science, and visualizing them can help you understand their inner workings. In this blog post, we will create an animated Bubble Sort visualization using Python and the matplotlib library.
Bubble Sort is a simple comparison-based sorting algorithm. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The process continues until the list is sorted.
Here’s how you can create an animated Bubble Sort using Python:
import matplotlib.pyplot as plt
import numpy as np
def bubble_sort_visual(arr):
fig, ax = plt.subplots()
ax.set_title("Bubble Sort Visualization")
bar_rects = ax.bar(range(len(arr)), arr, align="edge")
ax.set_xlim(0, len(arr))
ax.set_ylim(0, int(1.1 * max(arr)))
def update_rects(rects, heights):
for rect, h in zip(rects, heights):
rect.set_height(h)
def animate_sort():
for i in range(len(arr)):
for j in range(len(arr) - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
update_rects(bar_rects, arr)
plt.pause(0.1)
animate_sort()
plt.show()
arr = np.random.randint(1, 100, 30)
bubble_sort_visual(arr)
The code starts by creating a bar chart representing the list of numbers to be sorted. The bars are adjusted dynamically to reflect the sorting process. The animate_sort function performs the Bubble Sort algorithm, updating the bars with each swap.
To see the animation in action, you’ll need to have Python installed along with the matplotlib and numpy libraries. You can install these libraries using pip:
pip install matplotlib numpy
Once the libraries are installed, run the code, and you’ll see the sorting process visualized step by step.
Visualizing sorting algorithms like Bubble Sort can make learning them much easier. With Python and a few libraries, you can create these animations and gain a deeper understanding of how sorting works.