Sort Algorithm Visualization: How to pull values to animate the canvas, from inside a tight loop

前端 未结 2 1453
小鲜肉
小鲜肉 2020-12-21 14:51

I am working on a visualization of different sorting algorithms using the height of different bars with tkinter. I have been able to shuffle the bars and also sort them afte

2条回答
  •  盖世英雄少女心
    2020-12-21 15:07

    the time consuming function is "swap_two_pos()" which is catastrophic and you run it every loop, what you should do is finishing your sorting then redraw the bars again, below is your code modified working without GUI freeze, added a function and removed "swap_two_pos()" func.

    import tkinter as tk
    import random
    
    
    def insertion_sort():
        global barList
        global lengthList
    
        for i in range(len(lengthList)):
            cursor = lengthList[i]
            cursorBar = barList[i]
            pos = i
    
            while pos > 0 and lengthList[pos - 1] > cursor:
                lengthList[pos] = lengthList[pos - 1]
                barList[pos], barList[pos - 1] = barList[pos - 1], barList[pos]
                # canvas.after(1000,swap_two_pos(barList[pos],barList[pos-1]))
                pos -= 1
    
            lengthList[pos] = cursor
            barList[pos] = cursorBar
        refresh()
            # swap_two_pos(barList[pos],cursorBar)
    
    def refresh():
        canvas.delete('all')
        xstart = 5
        xend = 15
    
        for i, length in enumerate(lengthList): #range(1,60):
            y = random.randint(1,390)
            x = canvas.create_rectangle(xstart,length,xend,395, fill='red')
            barList.append(x)
            xstart += 10
            xend += 10
    
    
    def shuffle():
        global barList
        global lengthList
        canvas.delete('all')
        xstart = 5
        xend = 15
        barList = []
        lengthList = []
    
        for x in range(1,60):
            randomY = random.randint(1,390)
            x = canvas.create_rectangle(xstart,randomY,xend,395, fill='red')
            barList.append(x)
            xstart += 10
            xend += 10
    
        for bar in barList:
            x = canvas.coords(bar)
            length = x[3]-x[1]
            lengthList.append(length)
    
        for i in range(len(lengthList)-1):
            if lengthList[i] == min(lengthList):
                canvas.itemconfig(barList[i], fill='blue')
            elif lengthList[i] == max(lengthList):
                canvas.itemconfig(barList[i], fill='green')
    
    window = tk.Tk()
    window.title('Sorting')
    window.geometry('600x435')
    canvas = tk.Canvas(window, width='600', height='400')
    canvas.grid(column=0,row=0, columnspan = 50)
    
    insert = tk.Button(window, text='Insertion Sort', command=insertion_sort)
    shuf = tk.Button(window, text='Shuffle', command=shuffle)
    insert.grid(column=1,row=1)
    shuf.grid(column=0, row=1)
    
    shuffle()
    window.mainloop()
    

提交回复
热议问题