The user wants to create a visualization tool for sorting algorithms. Let me create a comprehensive solution that:
Implements multiple sorting algorithms (quicksort, mergesort, bubblesort, and more)
Provides real-time visualization using matplotlib animation
Has a clean, modular structure
Shows comparisons, swaps, and timing information
Allows the user to select different algorithms and array sizes
I'll create a well-structured solution with:
A base class for sorting visualizer
Individual sorting algorithm implementations that yield states for visualization
Matplotlib animation for real-time updates
Color coding to show which elements are being compared/swapped
Statistics tracking (comparisons, swaps, time)
Let me write comprehensive code:
python
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
import random
import time
from typing import Generator, List, Tuple
from abc import ABC, abstractmethod
I'll create both a matplotlib-based version and optionally a pygame version for smoother visualization.
Let me create a comprehensive solution:
Main visualization class with matplotlib
Multiple sorting algorithms as generators
Color coding for different states
Statistics display
Controls for speed, array size, algorithm selection
Both interactive and command-line interfaces
I'll also provide a simpler tkinter/canvas version as an alternative since it might be easier to run for some users. # Sorting Algorithm Visualizer in Python
Here's a comprehensive sorting algorithm visualization tool with multiple implementations.
Full-Featured Visualizer with Matplotlib
python
"""
Sorting Algorithm Visualizer
============================
Real-time visualization of various sorting algorithms using matplotlib.
"""
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.widgets import Button, Slider, RadioButtons
import numpy as np
import random
import time
from typing import Generator, List, Tuple, Optional
from dataclasses import dataclass
from enum import Enum, auto
class ElementState(Enum):
"""State of an element during sorting"""
NORMAL = auto()
COMPARING = auto()
SWAPPING = auto()
SORTED = auto()
PIVOT = auto()
CURRENT = auto()
@dataclass
class SortingStep:
"""Represents a single step in the sorting process"""
array: List[int]
highlights: dict # {index: ElementState}
comparisons: int
swaps: int
message: str = ""
class SortingAlgorithm:
"""Base class for sorting algorithms"""
def __init__(self, array: List[int]):
self.array = array.copy()
self.comparisons = 0
self.swaps = 0
self.array_accesses = 0
def swap(self, i: int, j: int) -> None:
"""Swap two elements"""
self.array[i], self.array[j] = self.array[j], self.array[i]
self.swaps += 1
self.array_accesses += 4 # 2 reads, 2 writes
def compare(self, i: int, j: int) -> bool:
"""Compare two elements"""
self.comparisons += 1
self.array_accesses += 2
return self.array[i] > self.array[j]
def compare_values(self, a: int, b: int) -> bool:
"""Compare two values directly"""
self.comparisons += 1
return a > b
class BubbleSort(SortingAlgorithm):
"""Bubble Sort - O(n²) time, O(1) space"""
@property
def name(self) -> str:
return "Bubble Sort"
def sort(self) -> Generator[SortingStep, None, None]:
n = len(self.array)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
# Highlight elements being compared
yield SortingStep(
array=self.array.copy(),
highlights={j: ElementState.COMPARING, j + 1: ElementState.COMPARING},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Comparing indices {j} and {j + 1}"
)
if self.compare(j, j + 1):
# Highlight swap
yield SortingStep(
array=self.array.copy(),
highlights={j: ElementState.SWAPPING, j + 1: ElementState.SWAPPING},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Swapping {self.array[j]} and {self.array[j + 1]}"
)
self.swap(j, j + 1)
swapped = True
if not swapped:
break
# Final sorted state
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SORTED for i in range(n)},
comparisons=self.comparisons,
swaps=self.swaps,
message="Sorting complete!"
)
class SelectionSort(SortingAlgorithm):
"""Selection Sort - O(n²) time, O(1) space"""
@property
def name(self) -> str:
return "Selection Sort"
def sort(self) -> Generator[SortingStep, None, None]:
n = len(self.array)
for i in range(n):
min_idx = i
# Find minimum element
for j in range(i + 1, n):
yield SortingStep(
array=self.array.copy(),
highlights={
i: ElementState.CURRENT,
min_idx: ElementState.PIVOT,
j: ElementState.COMPARING,
**{k: ElementState.SORTED for k in range(i)}
},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Finding minimum from index {i}"
)
self.comparisons += 1
if self.array[j] < self.array[min_idx]:
min_idx = j
# Swap minimum element with first unsorted element
if min_idx != i:
yield SortingStep(
array=self.array.copy(),
highlights={
i: ElementState.SWAPPING,
min_idx: ElementState.SWAPPING,
**{k: ElementState.SORTED for k in range(i)}
},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Swapping {self.array[i]} with minimum {self.array[min_idx]}"
)
self.swap(i, min_idx)
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SORTED for i in range(n)},
comparisons=self.comparisons,
swaps=self.swaps,
message="Sorting complete!"
)
class InsertionSort(SortingAlgorithm):
"""Insertion Sort - O(n²) time, O(1) space"""
@property
def name(self) -> str:
return "Insertion Sort"
def sort(self) -> Generator[SortingStep, None, None]:
n = len(self.array)
for i in range(1, n):
key = self.array[i]
j = i - 1
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.CURRENT, **{k: ElementState.SORTED for k in range(i)}},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Inserting element {key} into sorted portion"
)
while j >= 0:
self.comparisons += 1
yield SortingStep(
array=self.array.copy(),
highlights={
j: ElementState.COMPARING,
j + 1: ElementState.CURRENT,
**{k: ElementState.SORTED for k in range(j)}
},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Comparing {key} with {self.array[j]}"
)
if self.array[j] <= key:
break
self.array[j + 1] = self.array[j]
self.swaps += 1
j -= 1
self.array[j + 1] = key
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SORTED for i in range(n)},
comparisons=self.comparisons,
swaps=self.swaps,
message="Sorting complete!"
)
class QuickSort(SortingAlgorithm):
"""Quick Sort - O(n log n) average, O(n²) worst case"""
@property
def name(self) -> str:
return "Quick Sort"
def sort(self) -> Generator[SortingStep, None, None]:
yield from self._quicksort(0, len(self.array) - 1)
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SORTED for i in range(len(self.array))},
comparisons=self.comparisons,
swaps=self.swaps,
message="Sorting complete!"
)
def _quicksort(self, low: int, high: int) -> Generator[SortingStep, None, None]:
if low < high:
pivot_idx, partition_gen = self._partition(low, high)
yield from partition_gen
# Get the actual pivot index from the generator
pivot_idx = self._last_pivot_idx
yield from self._quicksort(low, pivot_idx - 1)
yield from self._quicksort(pivot_idx + 1, high)
def _partition(self, low: int, high: int) -> Tuple[int, Generator]:
def partition_generator():
pivot = self.array[high]
i = low - 1
yield SortingStep(
array=self.array.copy(),
highlights={high: ElementState.PIVOT},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Pivot selected: {pivot}"
)
for j in range(low, high):
yield SortingStep(
array=self.array.copy(),
highlights={
high: ElementState.PIVOT,
j: ElementState.COMPARING,
**({i: ElementState.CURRENT} if i >= low else {})
},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Comparing {self.array[j]} with pivot {pivot}"
)
self.comparisons += 1
if self.array[j] <= pivot:
i += 1
if i != j:
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SWAPPING, j: ElementState.SWAPPING, high: ElementState.PIVOT},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Swapping {self.array[i]} and {self.array[j]}"
)
self.swap(i, j)
# Place pivot in correct position
if i + 1 != high:
yield SortingStep(
array=self.array.copy(),
highlights={i + 1: ElementState.SWAPPING, high: ElementState.SWAPPING},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Placing pivot in position {i + 1}"
)
self.swap(i + 1, high)
self._last_pivot_idx = i + 1
return 0, partition_generator()
class MergeSort(SortingAlgorithm):
"""Merge Sort - O(n log n) time, O(n) space"""
@property
def name(self) -> str:
return "Merge Sort"
def sort(self) -> Generator[SortingStep, None, None]:
yield from self._mergesort(0, len(self.array) - 1)
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SORTED for i in range(len(self.array))},
comparisons=self.comparisons,
swaps=self.swaps,
message="Sorting complete!"
)
def _mergesort(self, left: int, right: int) -> Generator[SortingStep, None, None]:
if left < right:
mid = (left + right) // 2
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.CURRENT for i in range(left, right + 1)},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Dividing array from {left} to {right}"
)
yield from self._mergesort(left, mid)
yield from self._mergesort(mid + 1, right)
yield from self._merge(left, mid, right)
def _merge(self, left: int, mid: int, right: int) -> Generator[SortingStep, None, None]:
left_arr = self.array[left:mid + 1]
right_arr = self.array[mid + 1:right + 1]
i = j = 0
k = left
while i < len(left_arr) and j < len(right_arr):
yield SortingStep(
array=self.array.copy(),
highlights={
**{idx: ElementState.COMPARING for idx in range(left, right + 1)},
k: ElementState.CURRENT
},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Merging: comparing {left_arr[i]} and {right_arr[j]}"
)
self.comparisons += 1
if left_arr[i] <= right_arr[j]:
self.array[k] = left_arr[i]
i += 1
else:
self.array[k] = right_arr[j]
j += 1
self.swaps += 1
k += 1
while i < len(left_arr):
self.array[k] = left_arr[i]
i += 1
k += 1
self.swaps += 1
while j < len(right_arr):
self.array[k] = right_arr[j]
j += 1
k += 1
self.swaps += 1
class HeapSort(SortingAlgorithm):
"""Heap Sort - O(n log n) time, O(1) space"""
@property
def name(self) -> str:
return "Heap Sort"
def sort(self) -> Generator[SortingStep, None, None]:
n = len(self.array)
# Build max heap
for i in range(n // 2 - 1, -1, -1):
yield from self._heapify(n, i)
# Extract elements from heap
for i in range(n - 1, 0, -1):
yield SortingStep(
array=self.array.copy(),
highlights={0: ElementState.SWAPPING, i: ElementState.SWAPPING},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Moving max {self.array[0]} to position {i}"
)
self.swap(0, i)
yield from self._heapify(i, 0)
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SORTED for i in range(n)},
comparisons=self.comparisons,
swaps=self.swaps,
message="Sorting complete!"
)
def _heapify(self, n: int, i: int) -> Generator[SortingStep, None, None]:
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n:
self.comparisons += 1
if self.array[left] > self.array[largest]:
largest = left
if right < n:
self.comparisons += 1
if self.array[right] > self.array[largest]:
largest = right
if largest != i:
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.COMPARING, largest: ElementState.COMPARING},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Heapifying: swapping {self.array[i]} and {self.array[largest]}"
)
self.swap(i, largest)
yield from self._heapify(n, largest)
class ShellSort(SortingAlgorithm):
"""Shell Sort - O(n log² n) time, O(1) space"""
@property
def name(self) -> str:
return "Shell Sort"
def sort(self) -> Generator[SortingStep, None, None]:
n = len(self.array)
gap = n // 2
while gap > 0:
yield SortingStep(
array=self.array.copy(),
highlights={},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Gap size: {gap}"
)
for i in range(gap, n):
temp = self.array[i]
j = i
while j >= gap:
self.comparisons += 1
yield SortingStep(
array=self.array.copy(),
highlights={j: ElementState.CURRENT, j - gap: ElementState.COMPARING},
comparisons=self.comparisons,
swaps=self.swaps,
message=f"Comparing elements {gap} apart"
)
if self.array[j - gap] <= temp:
break
self.array[j] = self.array[j - gap]
self.swaps += 1
j -= gap
self.array[j] = temp
gap //= 2
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SORTED for i in range(n)},
comparisons=self.comparisons,
swaps=self.swaps,
message="Sorting complete!"
)
class CocktailShakerSort(SortingAlgorithm):
"""Cocktail Shaker Sort - O(n²) time, O(1) space"""
@property
def name(self) -> str:
return "Cocktail Shaker Sort"
def sort(self) -> Generator[SortingStep, None, None]:
n = len(self.array)
start = 0
end = n - 1
swapped = True
while swapped:
swapped = False
# Forward pass
for i in range(start, end):
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.COMPARING, i + 1: ElementState.COMPARING},
comparisons=self.comparisons,
swaps=self.swaps,
message="Forward pass"
)
if self.compare(i, i + 1):
self.swap(i, i + 1)
swapped = True
if not swapped:
break
end -= 1
swapped = False
# Backward pass
for i in range(end - 1, start - 1, -1):
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.COMPARING, i + 1: ElementState.COMPARING},
comparisons=self.comparisons,
swaps=self.swaps,
message="Backward pass"
)
if self.compare(i, i + 1):
self.swap(i, i + 1)
swapped = True
start += 1
yield SortingStep(
array=self.array.copy(),
highlights={i: ElementState.SORTED for i in range(n)},
comparisons=self.comparisons,
swaps=self.swaps,
message="Sorting complete!"
)
class SortingVisualizer:
"""Main visualization class using matplotlib"""
# Color scheme
COLORS = {
ElementState.NORMAL: '#3498db', # Blue
ElementState.COMPARING: '#f39c12', # Orange
ElementState.SWAPPING: '#e74c3c', # Red
ElementState.SORTED: '#2ecc71', # Green
ElementState.PIVOT: '#9b59b6', # Purple
ElementState.CURRENT: '#1abc9c', # Teal
}
ALGORITHMS = {
'Bubble Sort': BubbleSort,
'Selection Sort': SelectionSort,
'Insertion Sort': InsertionSort,
'Quick Sort': QuickSort,
'Merge Sort': MergeSort,
'Heap Sort': HeapSort,
'Shell Sort': ShellSort,
'Cocktail Shaker': CocktailShakerSort,
}
def __init__(self, array_size: int = 50, interval: int = 50):
self.array_size = array_size
self.interval = interval
self.array = self._generate_array()
self.algorithm_name = 'Bubble Sort'
self.sorting_generator = None
self.is_sorting = False
self.animation = None
self._setup_figure()
def _generate_array(self, shuffle: bool = True) -> List[int]:
"""Generate array to sort"""
arr = list(range(1, self.array_size + 1))
if shuffle:
random.shuffle(arr)
return arr
def _setup_figure(self):
"""Setup matplotlib figure and widgets"""
self.fig = plt.figure(figsize=(14, 9))
self.fig.patch.set_facecolor('#2c3e50')
# Main plot area
self.ax = self.fig.add_axes([0.1, 0.25, 0.6, 0.65])
self.ax.set_facecolor('#34495e')
# Statistics display
self.stats_ax = self.fig.add_axes([0.75, 0.5, 0.22, 0.4])
self.stats_ax.set_facecolor('#34495e')
self.stats_ax.axis('off')
# Algorithm selection
self.radio_ax = self.fig.add_axes([0.75, 0.1, 0.22, 0.35])
self.radio_ax.set_facecolor('#34495e')
self.radio = RadioButtons(
self.radio_ax,
list(self.ALGORITHMS.keys()),
active=0,
activecolor='#3498db'
)
self.radio.on_clicked(self._on_algorithm_change)
# Style radio buttons
for label in self.radio.labels:
label.set_color('white')
label.set_fontsize(9)
# Control buttons
button_color = '#3498db'
hover_color = '#2980b9'
self.start_ax = self.fig.add_axes([0.1, 0.08, 0.12, 0.06])
self.start_button = Button(self.start_ax, 'Start', color=button_color, hovercolor=hover_color)
self.start_button.label.set_color('white')
self.start_button.on_clicked(self._on_start)
self.pause_ax = self.fig.add_axes([0.24, 0.08, 0.12, 0.06])
self.pause_button = Button(self.pause_ax, 'Pause', color=button_color, hovercolor=hover_color)
self.pause_button.label.set_color('white')
self.pause_button.on_clicked(self._on_pause)
self.reset_ax = self.fig.add_axes([0.38, 0.08, 0.12, 0.06])
self.reset_button = Button(self.reset_ax, 'Reset', color=button_color, hovercolor=hover_color)
self.reset_button.label.set_color('white')
self.reset_button.on_clicked(self._on_reset)
self.shuffle_ax = self.fig.add_axes([0.52, 0.08, 0.12, 0.06])
self.shuffle_button = Button(self.shuffle_ax, 'Shuffle', color=button_color, hovercolor=hover_color)
self.shuffle_button.label.set_color('white')
self.shuffle_button.on_clicked(self._on_shuffle)
# Speed slider
self.speed_ax = self.fig.add_axes([0.1, 0.02, 0.54, 0.03])
self.speed_slider = Slider(
self.speed_ax, 'Speed', 1, 200,
valinit=100, valstep=1,
color='#3498db'
)
self.speed_slider.label.set_color('white')
self.speed_slider.valtext.set_color('white')
self.speed_slider.on_changed(self._on_speed_change)
# Initial draw
self._draw_array()
self._update_stats(0, 0, "Ready")
def _draw_array(self, highlights: dict = None):
"""Draw the array as bars"""
self.ax.clear()
self.ax.set_facecolor('#34495e')
n = len(self.array)
colors = []
for i in range(n):
if highlights and i in highlights:
colors.append(self.COLORS[highlights[i]])
else:
colors.append(self.COLORS[ElementState.NORMAL])
bars = self.ax.bar(
range(n),
self.array,
color=colors,
edgecolor='#2c3e50',
linewidth=0.5
)
self.ax.set_xlim(-1, n)
self.ax.set_ylim(0, max(self.array) * 1.1)
self.ax.set_title(f'{self.algorithm_name}', fontsize=14, color='white', fontweight='bold')
self.ax.tick_params(colors='white')
self.ax.spines['bottom'].set_color('white')
self.ax.spines['left'].set_color('white')
self.ax.spines['top'].set_visible(False)
self.ax.spines['right'].set_visible(False)
return bars
def _update_stats(self, comparisons: int, swaps: int, message: str):
"""Update statistics display"""
self.stats_ax.clear()
self.stats_ax.set_facecolor('#34495e')
self.stats_ax.axis('off')
stats_text = f"""
╔══════════════════════╗
║ STATISTICS ║
╠══════════════════════╣
║ Comparisons: {comparisons:>7} ║
║ Swaps: {swaps:>7} ║
║ Array Size: {len(self.array):>7} ║
╚══════════════════════╝
"""
self.stats_ax.text(
0.5, 0.7, stats_text,
transform=self.stats_ax.transAxes,
fontsize=10,
color='#ecf0f1',
family='monospace',
verticalalignment='center',
horizontalalignment='center'
)
# Status message
self.stats_ax.text(
0.5, 0.2, message,
transform=self.stats_ax.transAxes,
fontsize=9,
color='#f39c12',
verticalalignment='center',
horizontalalignment='center',
wrap=True
)
def _on_algorithm_change(self, label):
"""Handle algorithm selection change"""
self.algorithm_name = label
self._on_reset(None)
def _on_start(self, event):
"""Start sorting animation"""
if not self.is_sorting:
self.is_sorting = True
algorithm_class = self.ALGORITHMS[self.algorithm_name]
algorithm = algorithm_class(self.array)
self.sorting_generator = algorithm.sort()
self.animation = animation.FuncAnimation(
self.fig,
self._animate,
interval=max(1, 200 - self.speed_slider.val),
blit=False,
repeat=False
)
self.fig.canvas.draw()
def _on_pause(self, event):
"""Pause/resume animation"""
if self.animation:
if self.is_sorting:
self.animation.event_source.stop()
self.is_sorting = False
self.pause_button.label.set_text('Resume')
else:
self.animation.event_source.start()
self.is_sorting = True
self.pause_button.label.set_text('Pause')
def _on_reset(self, event):
"""Reset visualization"""
if self.animation:
self.animation.event_source.stop()
self.is_sorting = False
self.sorting_generator = None
self.pause_button.label.set_text('Pause')
self._draw_array()
self._update_stats(0, 0, "Ready")
self.fig.canvas.draw()
def _on_shuffle(self, event):
"""Shuffle array"""
self._on_reset(None)
random.shuffle(self.array)
self._draw_array()
self.fig.canvas.draw()
def _on_speed_change(self, val):
"""Handle speed slider change"""
if self.animation:
self.animation.event_source.interval = max(1, 200 - val)
def _animate(self, frame):
"""Animation update function"""
if self.sorting_generator:
try:
step = next(self.sorting_generator)
self.array = step.array.copy()
self._draw_array(step.highlights)
self._update_stats(step.comparisons, step.swaps, step.message)
except StopIteration:
self.is_sorting = False
if self.animation:
self.animation.event_source.stop()
self._update_stats(0, 0, "Sorting complete!")
def run(self):
"""Run the visualization"""
plt.show()
# Alternative: Simpler Pygame-based visualizer
class PygameVisualizer:
"""
Alternative visualizer using Pygame for smoother animations.
Uncomment and run if you have pygame installed.
"""
def __init__(self, width=1200, height=700, array_size=100):
try:
import pygame
self.pygame = pygame
except ImportError:
print("Pygame not installed. Use: pip install pygame")
return
pygame.init()
self.width = width
self.height = height
self.array_size = array_size
self.screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Sorting Algorithm Visualizer")
self.array = list(range(1, array_size + 1))
random.shuffle(self.array)
self.bar_width = (width - 200) // array_size
self.max_height = height - 150
self.colors = {
'background': (44, 62, 80),
'bar': (52, 152, 219),
'comparing': (243, 156, 18),
'swapping': (231, 76, 60),
'sorted': (46, 204, 113),
'pivot': (155, 89, 182),
'text': (236, 240, 241)
}
self.font = pygame.font.Font(None, 24)
self.title_font = pygame.font.Font(None, 36)
def draw(self, highlights=None, stats=None, title=""):
"""Draw the current state"""
self.screen.fill(self.colors['background'])
# Draw title
title_surface = self.title_font.render(title, True, self.colors['text'])
self.screen.blit(title_surface, (20, 20))
# Draw stats
if stats:
stats_text = f"Comparisons: {stats['comparisons']} | Swaps: {stats['swaps']}"
stats_surface = self.font.render(stats_text, True, self.colors['text'])
self.screen.blit(stats_surface, (20, 60))
# Draw bars
for i, val in enumerate(self.array):
color = self.colors['bar']
if highlights:
if i in highlights.get('comparing', []):
color = self.colors['comparing']
elif i in highlights.get('swapping', []):
color = self.colors['swapping']
elif i in highlights.get('sorted', []):
color = self.colors['sorted']
elif i in highlights.get('pivot', []):
color = self.colors['pivot']
bar_height = int((val / self.array_size) * self.max_height)
x = 100 + i * self.bar_width
y = self.height - 50 - bar_height
self.pygame.draw.rect(
self.screen,
color,
(x, y, max(1, self.bar_width - 1), bar_height)
)
self.pygame.display.flip()
def bubble_sort_visual(self):
"""Visualized bubble sort"""
n = len(self.array)
comparisons = 0
swaps = 0
for i in range(n):
for j in range(0, n - i - 1):
for event in self.pygame.event.get():
if event.type == self.pygame.QUIT:
return
comparisons += 1
self.draw(
highlights={'comparing': [j, j + 1]},
stats={'comparisons': comparisons, 'swaps': swaps},
title="Bubble Sort"
)
self.pygame.time.wait(1)
if self.array[j] > self.array[j + 1]:
self.array[j], self.array[j + 1] = self.array[j + 1], self.array[j]
swaps += 1
self.draw(
highlights={'swapping': [j, j + 1]},
stats={'comparisons': comparisons, 'swaps': swaps},
title="Bubble Sort"
)
self.pygame.time.wait(1)
self.draw(
highlights={'sorted': list(range(n))},
stats={'comparisons': comparisons, 'swaps': swaps},
title="Bubble Sort - Complete!"
)
def run(self):
"""Main loop"""
self.bubble_sort_visual()
running = True
while running:
for event in self.pygame.event.get():
if event.type == self.pygame.QUIT:
running = False
self.pygame.quit()
# Simple console-based visualizer for testing
class ConsoleVisualizer:
"""ASCII-based console visualization for environments without GUI"""
def __init__(self, array_size: int = 30):
self.array_size = array_size
self.array = list(range(1, array_size + 1))
random.shuffle(self.array)
def visualize(self, highlights: set = None, message: str = ""):
"""Display array as ASCII bars"""
import os
os.system('cls' if os.name == 'nt' else 'clear')
max_val = max(self.array)
height = 20
print("=" * 60)
print(message.center(60))
print("=" * 60)
print()
for row in range(height, 0, -1):
line = ""
for i, val in enumerate(self.array):
bar_height = int((val / max_val) * height)
if bar_height >= row:
if highlights and i in highlights:
line += "██"
else:
line += "░░"
else:
line += " "
print(line)
print("-" * (self.array_size * 2))
print()
def bubble_sort(self, delay: float = 0.05):
"""Visualized bubble sort"""
import time
n = len(self.array)
comparisons = 0
swaps = 0
for i in range(n):
for j in range(n - i - 1):
comparisons += 1
self.visualize(
highlights={j, j + 1},
message=f"Bubble Sort | Comparisons: {comparisons} | Swaps: {swaps}"
)
time.sleep(delay)
if self.array[j] > self.array[j + 1]:
self.array[j], self.array[j + 1] = self.array[j + 1], self.array[j]
swaps += 1
self.visualize(message=f"Complete! Comparisons: {comparisons} | Swaps: {swaps}")
def compare_algorithms(array_size: int = 100, num_trials: int = 3):
"""Compare performance of different sorting algorithms"""
import time
results = {}
for name, AlgorithmClass in SortingVisualizer.ALGORITHMS.items():
total_comparisons = 0
total_swaps = 0
total_time = 0
for _ in range(num_trials):
array = list(range(1, array_size + 1))
random.shuffle(array)
algo = AlgorithmClass(array)
start = time.perf_counter()
for step in algo.sort():
pass
end = time.perf_counter()
total_comparisons += step.comparisons
total_swaps += step.swaps
total_time += (end - start)
results[name] = {
'comparisons': total_comparisons // num_trials,
'swaps': total_swaps // num_trials,
'time': total_time / num_trials
}
# Display results
print("\n" + "=" * 70)
print(f"SORTING ALGORITHM COMPARISON (Array Size: {array_size}, Trials: {num_trials})")
print("=" * 70)
print(f"{'Algorithm':<22} {'Comparisons':>12} {'Swaps':>12} {'Time (s)':>12}")
print("-" * 70)
for name, stats in sorted(results.items(), key=lambda x: x[1]['comparisons']):
print(f"{name:<22} {stats['comparisons']:>12} {stats['swaps']:>12} {stats['time']:>12.6f}")
print("=" * 70)
return results
if __name__ == "__main__":
print("Sorting Algorithm Visualizer")
print("=" * 40)
print("1. Run GUI Visualizer (Matplotlib)")
print("2. Run Console Visualizer")
print("3. Compare Algorithms")
print("4. Run Pygame Visualizer")
choice = input("\nSelect option (1-4): ").strip()
if choice == "1":
visualizer = SortingVisualizer(array_size=50, interval=50)
visualizer.run()
elif choice == "2":
console_viz = ConsoleVisualizer(array_size=30)
console_viz.bubble_sort(delay=0.02)
elif choice == "3":
compare_algorithms(array_size=100, num_trials=3)
elif choice == "4":
pygame_viz = PygameVisualizer(array_size=100)
pygame_viz.run()
else:
# Default: run matplotlib visualizer
visualizer = SortingVisualizer(array_size=50)
visualizer.run()
Simpler Standalone Version (Tkinter)
python
Installation & Usage
bash
# Install required packages
pip install matplotlib numpy
# For the Tkinter version (usually included with Python)
# No additional installation needed
# For Pygame version (optional)
pip install pygame
# Run the visualizer
python sorting_visualizer.py