The most basic "bubble sort" of the alignment algorithm.
The origin of the name is "foam". It is gently sorted so that the bubbles come up. So let's create an animation that sorts bubbles with bubbles.
import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
fig = plt.figure()
ims = []
for _ in range(30):
image = []
for _ in range(30):
image += plt.plot(random.randint(10, 100), random.randint(10, 100),
markersize=random.randint(10, 100), marker="o", c="white",
markeredgecolor="blue", alpha=0.5)
ims.append(image)
#Convert to video
ani = animation.ArtistAnimation(fig, ims, interval=100, repeat_delay=1000)
ani.save("bubble.gif", writer='pillow') #Save as gif file
HTML(ani.to_jshtml()) #Display on HTML
Hey, it's foamy, isn't it? What did you imagine? Carbonated drinks? beer?
import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
def bubble_sort(data, x=0):
movie = [] #Video = list that stores a set of still images
image = []
for i in range(len(data)):
im1 = plt.plot(x, i, markersize=data[i], marker="o", c="white",
markeredgecolor="blue", alpha=0.5)
image += im1
movie.append(image) #Add one still image
for index in range(len(data)-1, 0, -1):
for low in range(index):
image = []
for i in range(len(data)):
if i == low or i == low + 1:
color = "skyblue"
else:
color = "white"
im1 = plt.plot(x, i, markersize=data[i], marker="o", c=color,
markeredgecolor="blue", alpha=0.5)
im2 = plt.plot(x, i, markersize=20, marker="$" + str(data[i]) + "$",
c="blue", alpha=0.5)
image += im2
image += im1
movie.append(image)
if data[low] > data[low+1]:
tmp = data[low+1]
data[low+1] = data[low]
data[low] = tmp
image = []
for i in range(len(data)):
if i == low or i == low + 1:
color="cyan"
else:
color="white"
im1 = plt.plot(x, i, markersize=data[i], marker="o", c=color, markeredgecolor="blue", alpha=0.5)
im2 = plt.plot(x, i, markersize=20, marker="$" + str(data[i]) + "$", c="blue", alpha=0.5)
image += im2
image += im1
movie.append(image)
return movie
data = [(i + 1) * 10 for i in range(10)]
random.shuffle(data)
fig = plt.figure(figsize=(8, 8))
movie1 = bubble_sort(data)
ani = animation.ArtistAnimation(fig, movie1, interval=1000, repeat_delay=1000)
ani.save("bubble_sort.gif", writer='pillow') #Save as gif file
HTML(ani.to_jshtml()) #Display on HTML
This is a bubble sort by all means. Thank you very much.
Yes, I did my best to make it. For sorting only.
Recommended Posts