VBA array sort function?

后端 未结 13 1986
北荒
北荒 2020-11-22 05:28

I\'m looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice.

<
13条回答
  •  被撕碎了的回忆
    2020-11-22 05:55

    Somewhat related, but I was also looking for a native excel VBA solution since advanced data structures (Dictionaries, etc.) aren't working in my environment. The following implements sorting via a binary tree in VBA:

    • Assumes array is populated one by one
    • Removes duplicates
    • Returns a separated string ("0|2|3|4|9") which can then be split.

    I used it for returning a raw sorted enumeration of rows selected for an arbitrarily selected range

    Private Enum LeafType: tEMPTY: tTree: tValue: End Enum
    Private Left As Variant, Right As Variant, Center As Variant
    Private LeftType As LeafType, RightType As LeafType, CenterType As LeafType
    Public Sub Add(x As Variant)
        If CenterType = tEMPTY Then
            Center = x
            CenterType = tValue
        ElseIf x > Center Then
            If RightType = tEMPTY Then
                Right = x
                RightType = tValue
            ElseIf RightType = tTree Then
                Right.Add x
            ElseIf x <> Right Then
                curLeaf = Right
                Set Right = New TreeList
                Right.Add curLeaf
                Right.Add x
                RightType = tTree
            End If
        ElseIf x < Center Then
            If LeftType = tEMPTY Then
                Left = x
                LeftType = tValue
            ElseIf LeftType = tTree Then
                Left.Add x
            ElseIf x <> Left Then
                curLeaf = Left
                Set Left = New TreeList
                Left.Add curLeaf
                Left.Add x
                LeftType = tTree
            End If
        End If
    End Sub
    Public Function GetList$()
        Const sep$ = "|"
        If LeftType = tValue Then
            LeftList$ = Left & sep
        ElseIf LeftType = tTree Then
            LeftList = Left.GetList & sep
        End If
        If RightType = tValue Then
            RightList$ = sep & Right
        ElseIf RightType = tTree Then
            RightList = sep & Right.GetList
        End If
        GetList = LeftList & Center & RightList
    End Function
    
    'Sample code
    Dim Tree As new TreeList
    Tree.Add("0")
    Tree.Add("2")
    Tree.Add("2")
    Tree.Add("-1")
    Debug.Print Tree.GetList() 'prints "-1|0|2"
    sortedList = Split(Tree.GetList(),"|")
    

提交回复
热议问题