VB排序算法-堆排序

'堆排序
Sub Heap(MyArray())
    Dim Index
    Dim size
    Dim temp
    
    '读取最大下标
    size = UBound(MyArray)
    '将当前要处理的置为1
    Index = 1
    '处理每一个元素
    While (Index <= size)
        '向上筛选
        Call HeapSiftup(MyArray(), Index)
        Index = Index + 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
    Wend
End Sub
'堆排序的向下筛选子程序
Sub HeapSiftdown(MyArray(), M)
    Dim Index
    Dim Parent
    Dim temp
    Index = 0
    'Parent位置定位于2 * Index
    Parent = 2 * Index
    Do While (Parent <= M)
        '如果当前Parent位的值后面的值要大,向后移Parent位
        If (Parent < M And MyArray(Parent) < MyArray(Parent + 1)) Then
            Parent = Parent + 1
        End If
        '如果当前值大于Parent位的值,结束筛选
        If MyArray(Index) >= MyArray(Parent) Then
            Exit Do
        End If
        '否则交换两个值
        temp = MyArray(Index)
        MyArray(Index) = MyArray(Parent)
        MyArray(Parent) = temp
        '当前位置移到Parent
        Index = Parent
        Parent = 2 * Index
    Loop
End Sub
'堆排序的向上筛选子程序
Sub HeapSiftup(MyArray(), M)
    Dim Index
    Dim Parent
    Dim temp
    Index = M
    Do While (Index > 0)
        '只要Index / 2位置的值大于当前值就结束筛选
        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 / 2
        Index = Parent
    Loop
End Sub

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值