曾经想制作动画来协助理解算法过程,可是感觉制作起来好麻烦。然后就想到了如果这个动画能通过代码生成,那岂不方便很多?于是就有了本文的尝试。当然,Excel表现力有限,所以在写完基本的排序算法动画之后,暂时就没做别的算法动画了。
以冒泡排序为例,效果如下:
实现代码如下:
vbnet
'为单元格设置背景色
Sub Color(row As Integer, col As Integer, clr As Long)
Worksheets("Sheet2").Cells(row, col).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = clr
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
'移动单元格
Sub CellMoveTo(rs As Integer, cs As Integer, re As Integer, ce As Integer)
Worksheets("Sheet2").Cells(rs, cs).Select
Selection.Cut
Worksheets("Sheet2").Cells(re, ce).Select
ActiveSheet.Paste
End Sub
'睡眠函数
Sub Sleep(t As Single) ' T 参数的单位是 秒级
Dim time1 As Single
time1 = Timer
Do
DoEvents '转让控制权,以便让操作系统处理其它的事件
Loop While Timer - time1 < t ' T 参数的单位是 秒级
End Sub
'同一行两个单元格交换
Sub Swap(row As Integer, col1 As Integer, col2 As Integer)
Call CellMoveTo(row, col1, row - 2, col1)
Call Sleep(1)
Call CellMoveTo(row, col2, row - 1, col2)
Call Sleep(1)
Dim i%, j%
i = col1
j = col2
Do While i < col2
Call CellMoveTo(row - 2, i, row - 2, i + 1)
i = i + 1
Call CellMoveTo(row - 1, j, row - 1, j - 1)
j = j - 1
Call Sleep(1)
Loop
Call CellMoveTo(row - 1, col1, row, col1)
Call Sleep(1)
Call CellMoveTo(row - 2, col2, row, col2)
Call Sleep(1)
End Sub
'冒泡排序
Sub BubbleSort()
Dim i%, j%, mend%, row%
Dim clr1 As Long, clr2 As Long, clrf As Long
mend = 14
row = 7
clr1 = 5287936
clr2 = 49407
clrf = 15773696
For i = 5 To 13
For j = 5 To mend - 1
Call Color(row, j, clr2)
Call Color(row, j + 1, clr2)
Call Sleep(1)
If Worksheets("Sheet2").Cells(row, j).Value > Worksheets("Sheet2").Cells(row, j + 1).Value Then
Call Swap(row, j, j + 1)
End If
Call Color(row, j, clr1)
Call Color(row, j + 1, clr1)
Call Sleep(1)
Next j
Call Color(row, mend, clrf)
mend = mend - 1
Call Sleep(1)
Next i
Call Color(row, mend, clrf)
End Sub
BubbleSort子过程实现了冒泡排序的动画效果。因为只是一个示意动画,所以我把页面固定为"Sheet2",排序的单元格固定为第7行,第5~14列的单元格。Color子过程主要用于给单元格着色。在整个排序过程中,我用了3中颜色,分别为初始颜色(绿色),比较大小时的颜色(橙色)和完成排序的颜色(蓝色)。CellMoveTo子过程利用单元格的"剪切"和"复制"功能完成单元格的移动。Swap子过程为同一行两个单元格交换做了一个简单的动画。Sleep子过程实现了以秒为单位的延时功能。