VB排序算法-希尔排序

'希尔排序
Sub ShellSort0(MyArray(), Optional ByVal SortByDesc As Boolean)
    Dim Distance
    Dim size
    Dim Index
    Dim NextElement
    Dim temp
    '读取元素的数量
    size = UBound(MyArray) - LBound(MyArray) + 1
    '定义当前跨度
    Distance = 1
    '将跨度定义为小于元素的数量的2的最大幂
    While (Distance <= size)
        Distance = 2 * Distance
    Wend
    '再找出跨度的中点
    Distance = (Distance / 2) - 1
    While (Distance > 0)
        '读取中点的下标
        NextElement = LBound(MyArray) + Distance
        '移排序并移动中点(不大于最大下标)
        While (NextElement <= UBound(MyArray))
            '将中点作为当前下标
            Index = NextElement
            Do
                '中点在跨度后面则要处理
                If Index >= (LBound(MyArray) + Distance) Then
                    '根据是升序或降序进行分别处理
                    If SortByDesc = False Then
                        '升序:如果当前值小于上一个值,则互换
                        If MyArray(Index) < MyArray(Index - Distance) Then
                            temp = MyArray(Index)
                            MyArray(Index) = MyArray(Index - Distance)
                            MyArray(Index - Distance) = temp
                            Index = Index - Distance
                        Else
                            Exit Do
                        End If
                    ElseIf SortByDesc = True Then
                        '降序:如果当前值大于上一个值,则互换
                        If MyArray(Index) > MyArray(Index - Distance) Then
                            temp = MyArray(Index)
                            MyArray(Index) = MyArray(Index - Distance)
                            MyArray(Index - Distance) = temp
                            Index = Index - Distance
                        Else
                            Exit Do
                        End If
                    End If
                Else
                    Exit Do
                End If
            Loop
            NextElement = NextElement + 1
        Wend
        Distance = (Distance - 1) / 2
    Wend
End Sub
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值