Python & matplotlibでソートアルゴリズムを可視化

主語を大きく括った割にバブル、挿入、クイックの三種類しか用意してないです。

参考:python - Updating a matplotlib bar graph? - Stack Overflow

テンプレート

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from random import randint

N = 60  # 配列の数
y = np.random.rand(N)*100 # ランダムな列をソートする

# ここに処理を書く
def animated_func():
    ...
    # 描画更新
    for rect, h in zip(rects, x):
        rect.set_height(h)
    fig.canvas.draw()
    ...

fig = plt.figure()
win = fig.canvas.manager.window
win.after(50, animated_func)
plt.show()

バブルソート


def animated_bubblesort():
    rects = plt.bar(range(N), y, 1)
    for i in range(len(y)-1):
        for j in range(len(y)-1, i, -1):
            if(y[j-1] > y[j]):
                t = y[j]
                y[j] = y[j-1]
                y[j-1] = t
                fig.canvas.draw()
            for rect, h in zip(rects, y):
                rect.set_height(h)
    fig.canvas.draw()

挿入ソート


def animated_insertion():
    rects = plt.bar(range(N), y, 1)
    for i in range(0, len(y)):
        for j in range(len(y)-1, i, -1):
            if y[j-1] < y[j]:
                continue
            t = y[j]
            y[j] = y[j-1]
            y[j-1] = t
            for rect, h in zip(rects, y):
                rect.set_height(h)
            fig.canvas.draw()
    fig.canvas.draw()

クイックソート

コピペ。再帰があるのでアニメーションとの兼ね合いがちょっと面倒。
A python example: QuickSort


結び

動画の作り方。連番pngを書き出して、ImageMagickから、

convert *png sort.mpeg

した。YouTubeからshakyとか怒られたけどよくわかりません。
barをアニメーションさせる方法がなかなか分からなくて時間がかかった(animation.FuncAnimationで作る方法があるのだろうか? あったらいいのに)。
ちなみに公式には以下の方法が載っているが冗談は休み休み言えと思う。

animation example code: histogram.py — Matplotlib v1.1.0 documentation