How should I adjust my bubble sort algorithm in python tkinter? (visualizer project)

64 views Asked by At

My code almost works, but I suspect something is being overwritten in my enumerations. I noticed when debugging that I'm comparing the same indexes for ex i=0 and j=0 or i = 1 and j=1. Could this be the issue to my problem? If so how can I adjust my enumerations? enter image description here

full code: https://pastebin.com/UaEssaSP


def start_algo(bars, tick_time):

    #first bar in list
    #canvas.itemconfig(bars[0], fill='red')
    #canvas.itemconfig(bars[49], fill='blue')

   
    #Bubble sort
    for i, _ in enumerate(bars):
        _, y1_low ,_ ,_ = canvas.coords(bars[i])  #unpack
        for j, _ in enumerate(bars): 
                _, y1_curr, _ , _ = canvas.coords(bars[j])  #unpack
                if y1_curr < y1_low:
                    swap_bars(bars[i],bars[j])
                    bars[i], bars[j] = bars[j], bars[i]
                    
    


1

There are 1 answers

2
Delta de Dirac On BEST ANSWER

Your algorithm doesn't look like bubble sort. This way it seems to work fine:

for i in range(len(bars)-1, -1, -1):
    for j in range(0, i):
        _, y1_low ,_ ,_ = canvas.coords(bars[j+1])
        _, y1_curr, _ , _ = canvas.coords(bars[j])
        if y1_curr < y1_low:
            swap_bars(bars[j],bars[j+1])
            bars[j+1], bars[j] = bars[j], bars[j+1]

result:

enter image description here