Advertisement
AlfonsoPEREZ

insertion sort

Apr 25th, 2020
407
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. import tkinter as tk
  2. import random
  3.  
  4.  
  5. a = None
  6.  
  7. def insertion_sort():
  8.     global a
  9.     a = sort()
  10.     show()
  11.  
  12. def show():
  13.     global a
  14.     if a is not None:
  15.         try:
  16.             next(a)
  17.             window.after(10, show)
  18.         except:
  19.             a = None
  20.         finally:
  21.             window.after_cancel(show)
  22.  
  23. def swap(pos_0, pos_1):
  24.     Bar1x1, _, Bar1x2, _ = canvas.coords(pos_0)
  25.     Bar2x1, _, Bar2x2, _ = canvas.coords(pos_1)
  26.     canvas.move(pos_0, Bar2x1-Bar1x1, 0)
  27.     canvas.move(pos_1, Bar1x2-Bar2x2, 0)
  28.  
  29.  
  30. def sort():
  31.     global listt
  32.     global lengthList
  33.  
  34.     for i in range(len(lengthList)):
  35.         cursor = lengthList[i]
  36.         cursorBar = listt[i]
  37.         pos = i
  38.  
  39.         while pos > 0 and lengthList[pos - 1] > cursor:
  40.             lengthList[pos] = lengthList[pos - 1]
  41.             listt[pos], listt[pos - 1] =listt[pos - 1], listt[pos]
  42.             swap(listt[pos],listt[pos-1])
  43.             yield                      
  44.             pos -= 1                            
  45.  
  46.         lengthList[pos] = cursor
  47.         listt[pos] = cursorBar
  48.         swap(listt[pos],cursorBar)
  49.  
  50.  
  51.  
  52. def mix():
  53.     global listt
  54.     global lengthList
  55.     canvas.delete('all')
  56.     xstart = 5
  57.     xend = 15
  58.     listt = []
  59.     lengthList = []
  60.  
  61.     for x in range(1, 60):
  62.         randomY = random.randint(1, 390)
  63.         x = canvas.create_rectangle(xstart, randomY, xend, 395, fill='powderblue')
  64.         listt.append(x)
  65.         xstart += 10
  66.         xend += 10
  67.  
  68.     for bar in listt:
  69.         x = canvas.coords(bar)
  70.         length = x[3] - x[1]
  71.         lengthList.append(length)
  72.  
  73.  
  74.  
  75.  
  76. window = tk.Tk()
  77. window.title('Insertion Sort Sorting ALGORITHM')
  78. window.geometry('600x450')
  79. canvas = tk.Canvas(window, width='600', height='400')
  80. canvas.grid(column=0,row=0, columnspan = 50)
  81.  
  82. insert = tk.Button(window, text='SORT', command=insertion_sort)
  83. shuf = tk.Button(window, text='MIX', command=mix)
  84. insert.grid(column=49,row=1)
  85. shuf.grid(column=0, row=1)
  86.  
  87. mix()
  88. window.mainloop()
  89. #https://www.youtube.com/channel/UCQor7IURWM-lGT-tmFbFSCw
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement