'希尔排序
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
 

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐