Skip to content

Commit 8baff62

Browse files
Added a Merge Sort visualization in matplotlib
1 parent 3154e56 commit 8baff62

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

MergeSortVis.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
import matplotlib.pyplot as plt
2+
import numpy as np
3+
4+
5+
class Vis:
6+
def __init__(self, a=100, barcol='white'):
7+
self.amount = a
8+
self.barcol = barcol
9+
self.lst = []
10+
self.x = np.arange(0, self.amount, 1)
11+
self.highlights = np.full(self.amount, barcol)
12+
13+
vals = np.arange(self.amount)
14+
for i in vals:
15+
x = np.random.randint(0, len(vals))
16+
self.lst.append(vals[x])
17+
vals = np.delete(vals, x)
18+
self.lst = np.array(self.lst)
19+
20+
def display(self):
21+
plt.clf()
22+
plt.gcf().set_facecolor('black')
23+
plt.bar(self.x, self.lst, color=self.highlights)
24+
plt.axis('off')
25+
plt.pause(0.0001)
26+
27+
28+
def merge_sort(current: Vis, lo, hi):
29+
unsorted = current.lst[lo:hi]
30+
31+
if len(unsorted) < 2:
32+
return unsorted
33+
34+
left = merge_sort(current, lo, lo + round(len(unsorted)/2)).copy()
35+
right = merge_sort(current, lo + round(len(unsorted)/2), hi).copy()
36+
37+
l, r = 0, 0
38+
while l < len(left) and r < len(right):
39+
if left[l] < right[r]:
40+
current.lst[lo+l+r] = left[l]
41+
l += 1
42+
current.highlights[lo+l+r] = 'green'
43+
current.display()
44+
current.highlights[lo + l + r] = current.barcol
45+
else:
46+
current.lst[lo+l+r] = right[r]
47+
r += 1
48+
current.highlights[lo + l + r] = 'green'
49+
current.display()
50+
current.highlights[lo + l + r] = current.barcol
51+
52+
if l < len(left):
53+
for i in range(len(left[l:])):
54+
current.lst[lo+l+r+i] = left[l+i]
55+
current.highlights[lo + l + r] = 'green'
56+
current.display()
57+
current.highlights[lo + l + r] = current.barcol
58+
elif r < len(right):
59+
for i in range(len(right[r:])):
60+
current.lst[lo+l+r+i] = right[r+i]
61+
current.highlights[lo + l + r] = 'green'
62+
current.display()
63+
current.highlights[lo + l + r] = current.barcol
64+
65+
return current.lst[lo:hi]

0 commit comments

Comments
 (0)