1 回答
![?](http://img1.sycdn.imooc.com/54584dc4000118d302200220-100-100.jpg)
TA贡献1868条经验 获得超4个赞
Private Sub Command1_Click()
Dim a(3000000 - 1) As Integer, i As Long
Dim t0 As Date, t1 As Date
Randomize
For i = 0 To 3000000 - 1
a(i) = Int(Rnd * 1000)
Next
t0 = Now
Call Heap(a)
t1 = Now
MsgBox "排序3000000个随机数花费" & DateDiff("s", t0, t1) & "秒"
End Sub
Sub Heap(MyArray() As Integer)
Dim Index As Long
Dim Size As Long
Dim TEMP As Integer
Size = UBound(MyArray)
Index = 1
While (Index <= Size)
Call HeapSiftup(MyArray, Index)
Index = Index + 1
gIterations = gIterations + 1
Wend
Index = Size
While (Index > 0)
TEMP = MyArray(0)
MyArray(0) = MyArray(Index)
MyArray(Index) = TEMP
Call HeapSiftdown(MyArray(), Index - 1)
Index = Index - 1
gIterations = gIterations + 1
Wend
End Sub
Sub HeapSiftdown(MyArray() As Integer, M As Long)
Dim Index As Long
Dim Parent As Long
Dim TEMP As Integer
Index = 0
Parent = 2 * Index
Do While (Parent <= M)
If (Parent < M And MyArray(Parent) < MyArray(Parent + 1)) Then
Parent = Parent + 1
End If
If MyArray(Index) >= MyArray(Parent) Then
Exit Do
End If
TEMP = MyArray(Index)
MyArray(Index) = MyArray(Parent)
MyArray(Parent) = TEMP
Index = Parent
Parent = 2 * Index
gIterations = gIterations + 1
Loop
End Sub
Sub HeapSiftup(MyArray() As Integer, M As Long)
Dim Index As Long
Dim Parent As Long
Dim TEMP As Integer
Index = M
Do While (Index > 0)
Parent = Int(Index / 2)
If MyArray(Parent) >= MyArray(Index) Then
Exit Do
End If
TEMP = MyArray(Index)
MyArray(Index) = MyArray(Parent)
MyArray(Parent) = TEMP
Index = Parent
gIterations = gIterations + 1
Loop
End Sub
添加回答
举报