Visualize MergeSort In Python
I want to make a mergesort visualizer in python. I want to use turtle module. To draw a single bar i use the function draw_bar, and to draw the entire array there is the function d
Solution 1:
You would need to update your grafics every time your array is changed, meaning after each arr[k] = L[j]
This is however difficult to do in your current implementation, because your recursive function has no information about which part of the larger list it is operating on.
I would recommend to change the function so that it is always passed the compleat array as well as the start index and length of the part it will be working on:
def mergeSort(arr, start, length):
if length > 1:
mergeSort(arr, start, length/2)
mergeSort(arr, start+length/2, length/2)
etc.
Then you will be able to call drawbars
every time, your array changes.
EDIT:
The full code would look something like this:
def mergeSort(arr, start, length):
if length > 2:
mergeSort(arr, start, int(length/2))
mergeSort(arr, start+int(length/2), int(length/2))
print(start+int(length/2))
L = arr[start:start+int(length/2)]
R = arr[start+int(length/2):start+length]
i=0
j=0
k=0
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[start+k] = L[i]
draw_bars(myarray)
i += 1
else:
arr[start+k] = R[j]
draw_bars(myarray)
j += 1
k += 1
while i < len(L):
arr[start+k] = L[i]
draw_bars(myarray)
i += 1
k += 1
while j < len(R):
arr[start+k] = R[j]
draw_bars(myarray)
j += 1
k += 1
myarr = [2,345,2456,3456,56,34,5,78,34,5423,26487,324,1,3,4,5]
draw_bars(myarray)
mergeSort(myarr, 0 ,len(myarr))
print(myarr)
Post a Comment for "Visualize MergeSort In Python"