import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
def generate_data(n=50, max_val=100):
"""Generate random data for sorting visualization."""
return list(np.random.randint(1, max_val + 1, n))
def bubble_sort_gen(arr):
"""Generator for bubble sort, yielding array state after each swap."""
arr = arr[:]
n = len(arr)
for i in range(n):
swapped = False
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
yield arr[:]
if not swapped:
break
def quicksort_gen(arr):
"""Generator for quicksort, yielding array state after each swap in partition."""
def partition(lo, hi):
pivot = arr[hi]
i = lo - 1
for j in range(lo, hi):
if arr[j] <= pivot:
i += 1
if i != j:
arr[i], arr[j] = arr[j], arr[i]
yield arr[:]
i += 1
if i != hi:
arr[i], arr[hi] = arr[hi], arr[i]
yield arr[:]
return i
def qrec(lo, hi):
if lo < hi:
p = yield from partition(lo, hi)
yield from qrec(lo, p - 1)
yield from qrec(p + 1, hi)
arr = arr[:]
yield from qrec(0, len(arr) - 1)
def mergesort_gen(arr):
"""Generator for bottom-up mergesort, yielding array state after each merge step."""
n = len(arr)
arr = arr[:]
width = 1
while width < n:
for start in range(0, n, width * 2):
mid = min(start + width, n)
end = min(start + 2 * width, n)
left = arr[start:mid]
right = arr[mid:end]
i, j, k = 0, 0, start
while i < len(left) and j < len(right):
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
yield arr[:]
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
yield arr[:]
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
yield arr[:]
width *= 2
def visualize(alg_name, data=None, interval=50, n=50):
"""
Visualize the specified sorting algorithm in real-time.
Args:
- alg_name (str): 'bubble', 'quick', or 'merge'
- data (list, optional): Custom data to sort. Defaults to random.
- interval (int): Animation interval in ms.
- n (int): Size of random data if data not provided.
"""
if data is None:
data = generate_data(n)
sort_gen_name = alg_name + '_sort_gen'
if sort_gen_name not in globals():
raise ValueError(f"Algorithm '{alg_name}' not supported. Choose 'bubble', 'quick', or 'merge'.")
gen = globals()[sort_gen_name](data)
fig, ax = plt.subplots(figsize=(12, 6))
bars = ax.bar(range(len(data)), data, color='skyblue', edgecolor='navy', linewidth=0.5)
ax.set_ylim(0, max(data) + 5)
ax.set_xlim(-0.5, len(data) - 0.5)
ax.set_xticks(range(len(data)))
# ax.set_xticklabels(range(len(data))) # Optional: show indices
ax.set_xlabel('Index')
ax.set_ylabel('Value')
ax.set_title(f'{alg_name.title()} Sort Visualization')
ax.grid(True, alpha=0.3)
def animate(arr):
for bar, height in zip(bars, arr):
bar.set_height(height)
return bars
ani = FuncAnimation(fig, animate, frames=gen, interval=interval, blit=True, repeat=False, cache_frame_data=False)
plt.tight_layout()
plt.show()
if __name__ == "__main__":
print("Sorting Algorithm Visualizer")
print("Available algorithms: 'bubble', 'quick', 'merge'")
alg = input("Enter algorithm name: ").strip().lower()
try:
visualize(alg)
except ValueError as e:
print(e)
Usage Instructions
Run the script: python sorting_visualizer.py
Enter an algorithm name when prompted: bubble, quick, or merge.
Watch the real-time bar chart animation as the algorithm sorts the data.
Close the plot window to end.
Features
Real-time animation using FuncAnimation with generator-based frame updates.
Efficient updates with blit=True for smooth performance.
Customizable: Pass custom data, adjust interval (speed), or n (array size) to visualize().
Example: visualize('bubble', interval=100) for slower bubble sort.
Generates random data by default (50 elements, values 1-100).
Yields after every swap/merge step for detailed visualization.
Stays on the final sorted state after completion.
This code is self-contained, efficient for small-to-medium arrays (up to ~100), and highlights the step-by-step process clearly!