[PYTHON] Visualize the behavior of the sorting algorithm with matplotlib

Introduction

When researching sorting algorithms on the Internet, we often see animations that visualize the behavior of the algorithms. I thought it would be interesting if I could make such an animation myself, so I tried using matplotlib.

Premise

Source code

[Bubble Sort](https://ja.wikipedia.org/wiki/%E3%83%90%E3%83%96%E3%83%AB%E3%82%BD%E3%83%BC%E3% This is the code that outputs the behavior of 83% 88) to a gif animation.

import matplotlib.pyplot as plt
import matplotlib.animation as ani
from random import shuffle

COLOR_PINK = '#ffc0cb'
COLOR_GOSSIP = '#cbffc0'


def draw_bar(li, color=COLOR_PINK):
  x_axis = list(range(1, len(li) + 1))

  plt.bar(x_axis, li,
          tick_label=li, align='center', width=0.4, color=color)


def draw_frame(frame, sorted_li, steps):
  plt.clf()
  li = steps[frame]
  options = {'color': COLOR_GOSSIP} if li == sorted_li else {}
  draw_bar(steps[frame], **options)


def bubble_sort(li):
  sorted_li = list(li)
  steps = []

  for i in range(0, len(sorted_li)):
    for j in range(1, len(sorted_li) - i):
      if sorted_li[j - 1] > sorted_li[j]:
        sorted_li[j], sorted_li[j - 1] = sorted_li[j - 1], sorted_li[j]

      if len(steps) == 0 or steps[-1] != sorted_li:
        steps.append(list(sorted_li))

  return sorted_li, steps


if __name__ == '__main__':
  li = list(range(1, 11))
  shuffle(li)

  sorted_li, steps = bubble_sort(li)

  fig = plt.figure(figsize=(6.0, 6.0))

  #Make the sort result appear longer by 5 frames in the animation.
  # FuncAnimation()To repeat_There is a delay option, but this doesn't work.
  steps = steps + [steps[-1]] * 5

  anim = ani.FuncAnimation(fig, draw_frame,
                           fargs=(sorted_li, steps), frames=len(steps))
  anim.save('bubble_sort.gif', writer='imagemagick', fps=5)

animation

bubble_sort.gif

reference

Recommended Posts

Visualize the behavior of the sorting algorithm with matplotlib
Let's visualize the number of people infected with coronavirus with matplotlib
Align the size of the colorbar with matplotlib
See the behavior of drunkenness with reinforcement learning
Increase the font size of the graph with matplotlib
Add information to the bottom of the figure with Matplotlib
Visualize the range of interpolation and extrapolation with python
Visualize the characteristic vocabulary of a document with D3.js
Visualize the appreciation status of art works with OpenCV
Adjust the ratio of multiple figures with the matplotlib gridspec
behavior of matplotlib: histogram normed
[Neta] Sorting algorithm of O (1)
Change the style of matplotlib
Visualize the orbit of Hayabusa2
Visualize the results of decision trees performed with Python scikit-learn
Tank game made with python About the behavior of tanks
Reformat the timeline of the pandas time series plot with matplotlib
I implemented the FloodFill algorithm with TRON BATTLE of CodinGame.
Visualize the flow rate of tweets with Diamond + Graphite + Grafana
I wrote the basic operation of matplotlib with Jupyter Lab
Implementation of Dijkstra's algorithm with python
Unravel the mystery of matplotlib specgram
About the behavior of yield_per of SqlAlchemy
About the size of matplotlib points
Visualize the response status of the census 2020
Find the optimal value of a function with a genetic algorithm (Part 2)
Solving the Maze with Python-Supplement to Chapter 6 of the Algorithm Quick Reference-
Visualize the frequency of word occurrences in sentences with Word Cloud. [Python]
[Python] I tried to visualize the prize money of "ONE PIECE" over 100 million characters with matplotlib.
[Python] Set the graph range with matplotlib
Check the behavior of destructor in Python
Adjust the spacing between figures with Matplotlib
Behavior when returning in the with block
Compute the partition function with the sum-product algorithm
Adjust the bin width crisply and neatly with the histogram of matplotlib and seaborn
Algorithm Gymnastics 24 Middle of the Linked List
Visualize the boundary values of the multi-layer perceptron
Try the Variational-Quantum-Eigensolver (VQE) algorithm with Blueqat
Algorithm learned with Python 8th: Evaluation of algorithm
Search the maze with the python A * algorithm
Algorithm learned with Python 19th: Sorting (heapsort)
Visualize the effects of deep learning / regularization
Set the xticklabels color individually with matplotlib
The third night of the loop with for
The second night of the loop with for
Match the colorbar to the figure with matplotlib
Visualize the export data of Piyo log
I tried to predict the behavior of the new coronavirus with the SEIR model.
Count the number of characters with echo
Make common settings with subplot of matplotlib
I tried to easily visualize the tweets of JAWS DAYS 2017 with Python + ELK
I wanted to visualize 3D particle simulation with the Python visualization library Matplotlib.
Note: Prepare the environment of CmdStanPy with docker
About the behavior of copy, deepcopy and numpy.copy
About the X-axis notation of Matplotlib bar graphs
[Python] limit axis of 3D graph with Matplotlib
2016 The University of Tokyo Mathematics Solved with Python
Algorithm learned with Python 13th: Tower of Hanoi
Drawing tips with matplotlib on the server side
[Note] Export the html of the site with python.
Visualize the inner layer of a neural network