创建一个由数字 1~30 随机组合的一个长度为 15 的乱序数组,数组元素以直方图显示。添加两个按钮,一个用来单步演示查找过程,一个按钮用来重新初始化一组随机整数。排序结束时弹出对话框提示。
# coding: utf-8
# !/usr/bin/python
"""
@File : 实验四_4.py
@Author : jiaming
@Modify Time: 2019/11/13 18:37
@Contact : https://blog.csdn.net/weixin_39541632
@Version : 1.0
@Desciption : None
"""
import tkinter as tk
import random
import copy
import tkinter.messagebox
width = 30
x0 = 80
y0 = 350
j = 0
sortL = []
root = tk.Tk()
root.title("动画演示插入排序")
root.geometry('640x500+250+250')
root.resizable(False, False)
def insertSort():
"""
生成随机数组, 并且保存插入排序的每步结果, 保存到sortL
:param num:
:return:
"""
global sortL
num = [i for i in range(1, 31, 1)]
random.shuffle(num)
num = num[:15]
for i in range(1, len(num)):
key = num[i]
j = i - 1
while j >= 0 and key < num[j]:
num[j + 1] = num[j]
j -= 1
num[j + 1] = key
sortL.append(copy.deepcopy(num))
sortL.append(copy.deepcopy(num))
def draw():
global width, x0, y0, j, sortL
key = j
x0 = 80
print(sortL[j])
def step():
for i in range(15):
canvas.delete(str(i))
canvas.delete("string" + str(i))
draw()
stepBtn = tk.Button(root, text="单步排序", width=8, height=1, command=step)
stepBtn.place(x=200, y=420)
def reset():
global j
j = 0
sortL.clear()
insertSort()
draw()
resetBtn = tk.Button(root, text="重置数据", width=8, height=1, command=reset)
resetBtn.place(x=350, y=420)
canvas = tk.Canvas(root, bg='white', height=400, width=1000)
canvas.place(x=0, y=0)
for i in range(15):
if key == i:
canvas.create_rectangle(x0, y0 - sortL[j][i] * 10,
x0 + width, y0, width=3, fill='red',
tags=str(i))
else:
canvas.create_rectangle(x0, y0 - sortL[j][i] * 10, x0 + width,
y0, width=3, tags=str(i))
canvas.create_text(x0 + width // 2, y0 - sortL[j][i] * 10 -
width // 2, text=str(sortL[j][i]),
font="time 10 bold underline",
tags="string" + str(i))
x0 = x0 + width
if j == 14:
tk.messagebox.showinfo('信息', '排序完成')
j += 1
insertSort()
draw()
root.mainloop()