我在Python中实现了合并排序......
def mergesort(z):
if len(z) > 1:
mid = len(z)//2
leftPortion = z[:mid]
rightPortion = z[mid:]
mergesort(leftPortion)
mergesort(rightPortion)
l = 0 # Next position in rightPortion
r = 0 # Next position in leftPortion
i = 0 # Next position in z
while l < len(leftPortion) and r < len(rightPortion):
if leftPortion[l] <= rightPortion[r]:
z[i] = leftPortion[l]
l = l + 1
else:
z[i] = rightPortion[r]
r = r + 1
i = i + 1
while l < len(leftPortion):
z[i] = leftPortion[l]
l = l + 1
i = i + 1
while r < len(rightPortion):
z[i] = rightPortion[r]
r = r + 1
i = i + 1
...我希望'记录'原始列表的状态,z,因为排序执行所以我可以使用Matplotlib来绘制排序的动画。我已经为冒泡排序和插入排序实现了这个方法,但由于合并中的递归,无法弄清楚如何做到这一点。有人可以帮忙吗?
这就是我使用冒号排序的方式......
import matplotlib.pyplot as plot
from time import sleep
from random import shuffle
from copy import copy
from time import time
plot.ion()
def generatecolours(w):
max = 16581375 # 255**3
interval = int(max/len(w))
r = range(0,max,interval)
return ['#{0}'.format(hex(r[i])[2:].zfill(6)) for i in w]
def plotchart(x,y,title):
plot.clf()
plot.title(title)
plot.axis('off')
plot.bar(x,y,color=generatecolours(y))
plot.pause(0.0001)
sleep(pause)
def bubblesort():
n = len(z)
trace = [copy(z)]
while True:
swap = False
for i in range(n-1):
if z[i] > z[i+1]:
z[i],z[i+1] = z[i+1],z[i]
swap = True
trace.append(copy(z))
n = n - 1
if not swap or n == 1:
break
return trace
# Define number of items in the list
items = 16
# Pause between iterations (s)
pause = 0.2
# Define coordinates and shuffle y
x = [i for i in range(1,items+1)]
y = [i for i in range(1,items+1)]
shuffle(y)
# Time sort operation for copies of y
print('Bubble sort')
print('-----------')
z = copy(y)
print('Unsorted list : {0}'.format(','.join(map(str,z))))
plotchart(x,z,'Bubble Sort')
input('Press enter to start ...')
start = time()
trace = bubblesort()
for line in trace:
plotchart(x,line,'Bubble Sort')
print('Time elapsed : {:.3f}s'.format(time()-start))
print('Sorted list : {0}\n'.format(','.join(map(str,z))))
input('Press enter when ready ...')
感谢您的帮助。