用Python的matplotlib库来创建动画,实现快速排序并将其过程动态可视化。
[Python] 纯文本查看 复制代码 import matplotlib.pyplot as plt
import matplotlib.animation as animation
from random import shuffle
def quicksort(arr, start, end, frames):
if start >= end:
return
pivot_index = partition(arr, start, end)
frames.append(arr[:])
quicksort(arr, start, pivot_index-1, frames)
quicksort(arr, pivot_index+1, end, frames)
def partition(arr, start, end):
pivot_index = start
pivot = arr[end]
for i in range(start, end):
if arr[i] < pivot:
arr[i], arr[pivot_index] = arr[pivot_index], arr[i]
pivot_index += 1
arr[end], arr[pivot_index] = arr[pivot_index], arr[end]
return pivot_index
def animate(frames):
fig, ax = plt.subplots()
ax.set_title("Quick Sort")
bar_rects = ax.bar(range(len(frames[0])), frames[0], align="edge")
def update_fig(frame, rects, iteration):
for rect, val in zip(rects, frame):
rect.set_height(val)
iteration[0] += 1
return rects
anim = animation.FuncAnimation(fig, func=update_fig,
fargs=(bar_rects, [0]),
frames=frames, interval=50,
repeat=False)
plt.show()
# 创建随机数据
data = [x for x in range(1, 31)]
shuffle(data)
# 排序过程中的所有状态
frames = []
quicksort(data, 0, len(data)-1, frames)
# 生成动画
animate(frames)
快速排序的逻辑被封装在quicksort函数中,animate函数用于创建和显示排序过程的动画。可以通过修改data列表来改变输入数据,或者调整interval参数来改变动画的速度。 |