Comprehending the Objective
I'm starting to grasp the core of the task: crafting Python code that brings sorting algorithms to life visually. My focus is on creating a GUI – a place where bars dance to the tune of algorithms like Quicksort. I'm imagining how these bars will change position, reflecting each step of the sorting process, in real-time.
Mapping the Implementation
Now, I'm sketching out the code's structure. First, I'll need to represent the data to be sorted – a list of numbers – as bars in the GUI. Then, each sorting algorithm (Quicksort, etc.) needs its own function, designed to yield control back to the GUI after each comparison or swap so the plot can refresh. This "yield" approach is the key for real-time visualization within matplotlib.
Choosing the Libraries
I've decided to proceed with matplotlib for the main visualization, keeping it relatively simple. After assessing both matplotlib.animation and updating plots within the main loop, an interactive "yield" strategy looks the most promising. This will help the sorting algorithm to pause and update the plot. For the sake of performance and better user experience, I'll be implementing the same code with pygame afterwards.
Revisiting Algorithm Design
I'm now diving deeper into how to represent the algorithms. To ensure the GUI refreshes smoothly, I'll leverage Python generators. Each sort will be a generator, yielding control back to the visualization after each comparison or swap. I'll make sure each algorithm has a draw_func that updates the plot after each step. I am considering the intricacies of in-place and out-of-place algorithms like Merge Sort, and how to best illustrate each step.
Evaluating Design Choices
I'm now weighing the pros and cons of my approach. While matplotlib is straightforward, I'm concerned about performance, especially for larger datasets. The yield strategy looks promising for interactive updates, but I'm thinking about animation overhead. The color-coding strategy appears to be clear for the comparison highlighting. I should probably refactor and add pygame version of this code.
Designing the GUI Elements
I'm now contemplating how to integrate user input – elements like sliders to control the dataset size and speed, and a button to initiate the sort. I'll need to use matplotlib.widgets to create these interactive controls. It'll be essential to connect these widgets to the sorting functions, allowing real-time adjustments to the visualization.
Implementing the Visualization
I'm now starting to code the algorithms, ensuring each step updates the plot via a draw_func. I'm using generators, yielding control after each comparison or swap for real-time visualization, and will provide user control of the speed. The focus now is on implementing the draw function efficiently, to speed up the plotting.
This is a classic coding project. The most efficient way to do this in standard Python is using the matplotlib library. It handles the drawing and window management, while allowing us to pause execution briefly to create the "animation" effect.
Here is a complete, copy-paste runnable Python script. It includes Bubble Sort, Merge Sort, and Quick Sort.
Prerequisites
You usually have Python installed, but you will need matplotlib. If you don't have it, run:
pip install matplotlib
The Python Code
import matplotlib.pyplot as plt
import random
import time
class SortingVisualizer:
def __init__(self, n=50, speed=0.01):
self.n = n
self.speed = speed
# Generate random data
self.data = [random.randint(1, 100) for _ in range(self.n)]
self.x = range(self.n)
# Setup plot
self.fig, self.ax = plt.subplots()
self.ax.set_title("Sorting Visualizer")
self.bar_rects = self.ax.bar(self.x, self.data, align="edge")
self.text = self.ax.text(0.02, 0.95, "", transform=self.ax.transAxes)
self.iteration = [0]
def update_plot(self, data, colors, algo_name):
"""
Updates the bar chart.
data: list of height values
colors: list of colors for each bar
"""
for rect, val, color in zip(self.bar_rects, data, colors):
rect.set_height(val)
rect.set_color(color)
self.iteration[0] += 1
self.text.set_text(f"{algo_name} | Operations: {self.iteration[0]}")
plt.pause(self.speed)
# -----------------------------------
# ALGORITHMS
# -----------------------------------
def bubble_sort(self):
self.iteration[0] = 0
n = len(self.data)
for i in range(n):
for j in range(0, n - i - 1):
# Highlight bars being compared (Red)
colors = ['gray'] * n
colors[j] = 'red'
colors[j+1] = 'red'
self.update_plot(self.data, colors, "Bubble Sort")
if self.data[j] > self.data[j + 1]:
self.data[j], self.data[j + 1] = self.data[j + 1], self.data[j]
# Highlight swap (Green)
colors[j] = 'green'
colors[j+1] = 'green'
self.update_plot(self.data, colors, "Bubble Sort")
# Final finish (all blue)
self.update_plot(self.data, ['blue']*n, "Bubble Sort - Done")
plt.show()
def quick_sort(self, head, tail):
if head < tail:
# Partition the array and get the pivot index
partition_index = self.partition(head, tail)
# Recursively sort elements before and after partition
self.quick_sort(head, partition_index - 1)
self.quick_sort(partition_index + 1, tail)
def partition(self, head, tail):
pivot = self.data[tail]
i = head - 1
for j in range(head, tail):
# Highlight current comparison
colors = ['gray'] * len(self.data)
colors[j] = 'red'
colors[tail] = 'orange' # Pivot
self.update_plot(self.data, colors, "Quick Sort")
if self.data[j] < pivot:
i += 1
self.data[i], self.data[j] = self.data[j], self.data[i]
colors[i] = 'green' # Swap
colors[j] = 'green'
self.update_plot(self.data, colors, "Quick Sort")
self.data[i + 1], self.data[tail] = self.data[tail], self.data[i + 1]
return i + 1
def merge_sort(self, left, right):
if left < right:
mid = (left + right) // 2
self.merge_sort(left, mid)
self.merge_sort(mid + 1, right)
self.merge(left, mid, right)
def merge(self, left, mid, right):
# We make copies for merging logic
left_part = self.data[left:mid + 1]
right_part = self.data[mid + 1:right + 1]
i = j = 0
k = left
while i < len(left_part) and j < len(right_part):
colors = ['gray'] * len(self.data)
# Highlight the range being merged
for idx in range(left, right+1):
colors[idx] = 'purple'
colors[k] = 'red' # Writing position
self.update_plot(self.data, colors, "Merge Sort")
if left_part[i] <= right_part[j]:
self.data[k] = left_part[i]
i += 1
else:
self.data[k] = right_part[j]
j += 1
k += 1
# Flush remaining elements
while i < len(left_part):
self.update_plot(self.data, ['gray']*len(self.data), "Merge Sort")
self.data[k] = left_part[i]
i += 1
k += 1
while j < len(right_part):
self.update_plot(self.data, ['gray']*len(self.data), "Merge Sort")
self.data[k] = right_part[j]
j += 1
k += 1
# -----------------------------------
# DRIVER CODE
# -----------------------------------
def run(self):
print("Select Algorithm:")
print("1. Bubble Sort")
print("2. Quick Sort")
print("3. Merge Sort")
choice = input("Enter number (1-3): ")
if choice == '1':
self.bubble_sort()
elif choice == '2':
self.iteration[0] = 0
self.quick_sort(0, len(self.data)-1)
self.update_plot(self.data, ['blue']*len(self.data), "Quick Sort - Done")
plt.show()
elif choice == '3':
self.iteration[0] = 0
self.merge_sort(0, len(self.data)-1)
self.update_plot(self.data, ['blue']*len(self.data), "Merge Sort - Done")
plt.show()
else:
print("Invalid selection")
if __name__ == "__main__":
# Change 'n' for number of bars, 'speed' for delay in seconds
vis = SortingVisualizer(n=50, speed=0.001)
vis.run()
How it works
- The Setup (
__init__): We create a list of random integers. We initialize a Matplotlib bar chart. Notice self.bar_rects; this holds the reference to the rectangle objects so we can modify their height later without redrawing the whole chart (which would be slow).
- The
update_plot function: This is the visualization engine.
- It accepts the data and a list of colors.
- It sets the height of every bar to the new data values.
- It sets the color of bars (e.g., Red for comparing, Green for swapping).
- Crucially, it calls
plt.pause(time). This forces Matplotlib to update the window and wait, creating the animation frame.
- The Algorithms:
- Bubble Sort: Standard nested loops. We call
update_plot every time we compare or swap.
- Quick Sort: Standard recursive approach. Uses a partition function. We color the Pivot Orange.
- Merge Sort: This is tricky to visualize because standard Merge Sort creates new lists. I handle the visualization inside the
merge step where the data is written back to the main array self.data.
- Colors used:
- Gray: Idle / Unsorted portion.
- Red: Currently being compared or moved.
- Green: Just swapped.
- Orange: Key pivot (QuickSort).
- Blue: Final sorted state.
How to run it
- Save the code as a Python file (e.g.,
sorter.py).
- Run it in your terminal:
python sorter.py.
- Enter
1, 2, or 3 and hit Enter.
- A window will pop up showing the sort in action.
Note: If the animation is too slow or too fast, change the speed parameter in the last line: vis = SortingVisualizer(n=50, speed=0.001).