Hey so the code works perfectly thank you very much!
i just have one more question. I want to have an arrow displayed in between the two coulmns. i created this code but i dont really know how to make it go in between the columns that are being switched. any suggestions?
def arrow(lst, i): # function for the arrow
if (lst[i], lst[i+1] == lst[i+1], lst[i]):
t.home()
t.penup()
# im thinking something goes here but i dont know what :P
t.pendown()
t.pencolor("red")
t.right(90)
t.forward(20)
any help would be very appreciated! Thank you! btw the rest of the code is like imran's code! :) thank yoU!
your code looks a lot like one of the versions of bubble sort here. The main issue why your version isn't working is because you are comparing lst at index i with i-1 which fails when i=0. Change that section to:
if (lst[i] < lst[i + 1]):
swapped = False
lst[i+1], lst[i] = lst[i], lst[i+1]
Also, don't define n outside of the function (which should ideally be called bubble_sort, or something similar), that is bad programming, a bug waiting to happen. I don't know what you are trying to accomplish with lst = [lst]
. Might want to use a different variable name.
Edit: I made some liberal changes to your code. I put all the drawing call inside the bubble sort. The bubble sort also internally converts the list into a list of tuples where the second element of the tuple is the color. The for loop at the end of your code doesn't do anything worthwhile. I think your main issue was that it was not pausing between each iteration of the while loop so you don't get to see the elements of the list bubble up.
#!/usr/bin/python
import turtle as t
def draw(lst, width):
for x in lst:
height = x[0]
t.color(x[1])
t.forward(width)
t.left(90)
t.forward(height)
t.left(90)
t.forward(width)
t.left(90)
t.forward(height)
t.left(90)
t.penup()
t.forward(30)
t.pendown()
def bubble_sort(orig_lst):
lst = [ (x, "blue") for x in orig_lst ]
n = len(lst)-1
t.pensize(3)
draw(lst, width)
swapped = True
while swapped:
swapped = False
for i in range(n):
if lst[i+1][0] < lst[i][0]:
lst[i], lst[i+1] = lst[i+1], lst[i]
lst[i] = (lst[i][0], "green")
swapped = True
next = raw_input("hit any key to continue ")
t.home()
t.clear()
draw(lst,width)
newLst = [ x[0] for x in lst ]
return newLst
# TOP LEVEL
original_lst = input("Enter list to be sorted: ")
width = input("Provide the width: ")
newLst = bubble_sort(original_lst)
print "Done! Sorted list is: ", newLst
next = raw_input("hit any key to exit ")