Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Bubble Sort Algorithm Animation

$
0
0
Hi there, so I've been working on this code that will animate a bubble sort algorithm using bars. The one problem that i have is that i cant get the bars to do the animation 1 by one so that you can see the swap occurring. Right now the program will animate each swap set and then delete it so in the end you get the sorted bars but I want to make it so that only one bar is swaped each time. Here is what i want it to look like (this is my class website):

http://www.mmrelearning.ca/mod/page/view.php?id=4221

from Tkinter import*
import time

def sort():
    x =100
    y = 500
    barWidth = 15
    lst = [10, 25,5,15,30,20]

    for item in lst:
      
        bar = cv.create_rectangle(x, y, x+barWidth, y-(item*10), fill="red")
        x += barWidth + 5
        cv.update()
        
    x= 100
    y =500

    for item in range(len(lst)-1, 0, -1):
        for i in range(item):
            if lst[i] > lst[i + 1]:
                lst[i], lst[i + 1] = lst[i + 1], lst[i]
                print lst
                cv.delete(ALL)
                for bars in lst:
                    time.sleep(0.1) 
                    barSorted = cv.create_rectangle(x, y, x+barWidth, y-(bars*10), fill="red")
                    x += barWidth + 5
                    cv.update()
        
#MAIN

#Canvas                    
root = Tk()
root.title("Sorting Algorithm Animation")
w = 800
h = 600
cv = Canvas(width=w, height=h, bg='black')

cv.pack()
cv.update()
sort()
root.mainloop()



Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>