插入排序的Python代码
import tkinter as tk
import random
import time
class InsertionSortVisualizer :
def __init__ ( self, root, canvas_width= 800 , canvas_height= 400 , num_bars= 10 ) :
self. root = root
self. canvas_width = canvas_width
self. canvas_height = canvas_height
self. num_bars = num_bars
self. bar_width = canvas_width // num_bars
self. data = [ random. randint( 1 , canvas_height) for _ in range ( num_bars) ]
self. canvas = tk. Canvas( root, width= canvas_width, height= canvas_height)
self. canvas. pack( )
self. draw_data( )
def draw_data ( self, colored_index= None ) :
self. canvas. delete( "all" )
for i, value in enumerate ( self. data) :
if colored_index is not None and i in colored_index:
color = "red"
else :
color = "blue"
self. canvas. create_rectangle( i * self. bar_width, self. canvas_height - value,
( i + 1 ) * self. bar_width, self. canvas_height,
fill= color)
self. root. update_idletasks( )
def insertion_sort ( self) :
for i in range ( 1 , len ( self. data) ) :
key = self. data[ i]
self. draw_data( [ i] )
j = i - 1
while j >= 0 and key < self. data[ j] :
self. data[ j + 1 ] = self. data[ j]
j -= 1
self. data[ j + 1 ] = key
self. draw_data( [ j + 1 ] )
time. sleep( 0.5 )
self. draw_data( )
def main ( ) :
root = tk. Tk( )
root. title( "插入排序" )
app = InsertionSortVisualizer( root)
tk. Button( root, text= "开始" , command= app. insertion_sort) . pack( )
root. mainloop( )
if __name__ == "__main__" :
main( )
运行结果