Skip to content

Instantly share code, notes, and snippets.

@asnramos
Created July 23, 2020 04:26
Show Gist options
  • Save asnramos/02110f3404315498da577afcb6d549d3 to your computer and use it in GitHub Desktop.
Save asnramos/02110f3404315498da577afcb6d549d3 to your computer and use it in GitHub Desktop.
Sorting algo
import random
import matplotlib.animation as animation
from matplotlib import pyplot
import numpy as np
### Plot adjusting
pyplot.style.use("ggplot")
fig, g = pyplot.subplots(figsize=(9,6))
pyplot.subplots_adjust(top = 0.93, left = 0.07, right = 0.93, bottom = 0.07)
pyplot.rcParams['axes.facecolor'] = "gray"
pyplot.rcParams['savefig.facecolor'] = "whitesmoke"
n = 80 # Number of elements
lstA = list(np.arange(1,n+1,1)) # Correct order list
lstB = lstA.copy() # Copy of correct order list
random.shuffle( lstB ) # Randomly sorted new list
### Sorting
r = [] # Result list
r.append(lstB.copy())
t1 = lstA == lstB # Test 1
while t1 == False :
for p in range(0,len(lstA)-1) :
t2 = lstB[p] > lstB[p+1] # Test 2
if t2 == True :
lstB[p] , lstB[p+1] = lstB[p+1] , lstB[p] # Swap position
r.append(lstB.copy())
t1 = lstA == lstB
### End sorting
### Coloring
c = [] # Color list
cmp = pyplot.cm.jet # Colormap to be used
mp = int(300/n) # Multiplier to spread the colors)
for cl in range(0,len(r)) :
tc = [] # Transfer list
for sh in r[cl] :
tc.append(cmp(sh*mp))
c.append(tc)
### End coloring
ctd = 0 # Counter
def update(*args) : # Animation function
global ctd
pyplot.clf()
pyplot.bar(lstA, r[ctd], color =c[ctd], align = 'center')
pyplot.title("Iteration : " + str(ctd+1), fontsize = 10, loc = "right")
pyplot.grid(False)
pyplot.xlim(0,n+1)
pyplot.ylim(0,n+1)
pyplot.yticks([])
ctd +=1
if ctd > len(r)-1 : # Counter cannot be higer than the result list size
ctd = len(r)-1 # due to interval frames - "+8" below
return ()
def init() :
return()
anim = animation.FuncAnimation(fig, update, init_func=init, blit = True, frames=len(r)+8, repeat = False)
sf = "Sorting.gif"
Sname = "C:\\Users\\Rober\\Desktop\\_" + sf # Change to your directory
anim.save(Sname, writer="imagemagick", fps=4)
# You must have imagemagick installed in you computer :
# https://www.imagemagick.org/script/index.php
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment