I Built This Project in Python and Used Matplotlib Bar Charts to Plot a Random List and Then Animated The Charts to Sort The Bars Using Each Algorithm. It Currently Can Visualize Insertion Sort, Bubble Sort, Selection Sort, and Merge Sort.
from random import random import matplotlib.pyplot as plt def insertion_sort(lst): n = range(len(lst)) i = 1 while i < len(lst): j = i-1 while j >= 0: plt.clf() plt.title("Insertion Sort") plt.bar(n, lst) plt.pause(0.001) if lst[j+1] < lst[j]: lst[j+1], lst[j] = lst[j], lst[j+1] else: break j-=1 i+=1 plt.show() def bubble_sort(lst): n = range(len(lst)) i = 0 while i < len(lst): j = 0 while j < len(lst)-i-1: plt.clf() plt.title("Bubble Sort") plt.bar(n, lst) plt.pause(0.001) if lst[j] > lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] j+=1 i+=1 plt.show() def selection_sort(lst): n = range(len(lst)) curr_min = 0 curr_i = 0 i = 0 while i < len(lst): plt.clf() plt.title("Selection Sort") bars = plt.bar(n, lst) curr_i = i curr_min = i while curr_i < len(lst): for bar in bars: bar.set_color("#1F77B4") bars[curr_min].set_color("red") bars[curr_i].set_color("#FAB143") plt.pause(0.01) if lst[curr_i] < lst[curr_min]: curr_min = curr_i curr_i+=1 lst[i], lst[curr_min] = lst[curr_min], lst[i] i+=1 plt.show() def merge(lst, left_lmt, mid, right_lmt): left_counter = left_lmt right_counter = mid while left_counter < right_counter and right_counter < right_lmt: if lst[left_counter] > lst[right_counter]: item = lst.pop(right_counter) lst.insert(left_counter, item) right_counter+=1 left_counter+=1 plt.clf() plt.title("Merge Sort") plt.bar(n, lst) plt.pause(0.01) else: left_counter+=1 while right_counter < right_lmt: item = lst.pop(right_counter) lst.insert(left_counter, item) right_counter+=1 left_counter+=1 plt.clf() plt.title("Merge Sort") plt.bar(n, lst) plt.pause(0.01) return lst def merge_sort(lst, left_lmt, right_lmt): if right_lmt - left_lmt > 1: mid = int((left_lmt + right_lmt) / 2) lst = merge_sort(lst, left_lmt, mid) lst = merge_sort(lst, mid, right_lmt) lst = merge(lst, left_lmt, mid, right_lmt) return lst print("Welcome to The Sorting Algorithm Visualizer.") print("Type The Name of The Algorithm You Would Like to Visualize, Or Type Exit to Quit") print("Options Include: Insertion Sort, Bubble Sort, Selection Sort, Merge Sort") while True: lst = [] for i in range(45): lst.append(random()) algorithm = input() match algorithm: case "Insertion Sort": insertion_sort(lst) case "Bubble Sort": bubble_sort(lst) case "Selection Sort": selection_sort(lst) case "Merge Sort": n = range(len(lst)) plt.clf() plt.title("Merge Sort") plt.bar(n, lst) plt.pause(0.1) sorted_lst = merge_sort(lst, 0, len(lst)) plt.show() case "Exit": break case _: print("value not recognized")