import pylab
from random import shuffle
def bubblesort_anim(a):
x = range(len(a))
imgidx = 0
# bubble sort algorithm
swapped = True
while swapped: # until there's no swapping
swapped = False
for i in range(len(a)-1):
if a[i] > a[i+1]:
a[i+1], a[i] = a[i], a[i+1] # swap
swapped = True
pylab.plot(x,a,'k.',markersize=6)
pylab.savefig("bubblesort/img" + '%04d' % imgidx + ".png")
pylab.clf() # figure clear
imgidx = imgidx + 1
# running the algorithm
a = range(300)
shuffle(a)
bubblesort_anim(a)
The snipped is based same technique we have seen to visualize the insertion sort algorithm and to build the animation. At each iteration an image that represents the status of the array is saved to the disk and ffmpeg is used to build a video as showed in the last post. This time the result should be as follows:Stay tuned to see the animation of the insertion sort algorithm!
Nice visualization. One of the great strengths of Python is that it is possible to produce such things with such a small amount of code.
ReplyDeleteThis code doesn't work in python 3.2 due to the range type being changed.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDelete