选择排序算法
冒泡排序算法
原理:数字两两进行比较,将大的值移动到右侧,继续进行比较直到最大值移动到最右侧,则完成一次循环,进入第二次循环,以此类推,直到全部数字排序完成。
import turtle
import time
myPen = turtle.Pen()
myPen.pensize(15)
List = [15, 60, 85, 165, 10, 70, 5]
dis = [0, 50, 100, 150, 200, 250, 300]
# myPen.penup()
# myPen.goto(dis[0], 0)
# myPen.pendown()
# myPen.left(90)
# myPen.forward(List[0])
def draw_line(x):
myPen.goto(dis[x], 0)
myPen.pendown()
myPen.setheading(90)
myPen.forward(List[x])
myPen.penup()
# for i in range(len(List)):
# draw_line(i)
# List = [3, 2, 4, 1]
count = 0
for j in range(len(List)-1):
for i in range(len(List)-1-j):
max = List[i]
if List[i] > List[i+1]:
List[i], List[i+1] = List[i+1], List[i]
myPen.clear()
for m in range(len(List)):
if m == i or m == i+1:
myPen.pencolor("green")
draw_line(m)
else:
myPen.pencolor("blue")
draw_line(m)
time.sleep(1.5)
# count += 1
print(List,count)
turtle.done()
网友评论