Counting Sort

Public Sub Countingsort(list) 
    Dim counts() As Long
    Dim i As Long
    Dim j As Long
    Dim next_index As Long
    Dim min, max
    Dim min_value As Variant, max_value As Variant

' Allocate the counts array. VBA automatically
' initialises all entries to 0.

    min_value = Minimum(list)
    max_value = Maximum(list)
    
    min = LBound(list)
    max = UBound(list)
    
    ReDim counts(min_value To max_value)
    
' Count the values.
    For i = min To max
        counts(list(i)) = counts(list(i)) + 1
    Next i

' Write the items back into the list array.
    next_index = min
    For i = min_value To max_value
        For j = 1 To counts(i)
            list(next_index) = i
            next_index = next_index + 1
        Next j
    Next i
End Sub

Private Function Maximum(l)
    Dim s1, s2
    Dim i
    s1 = LBound(l)
    s2 = UBound(l)
    Maximum = l(s1)
    For i = s1 To s2
        If l(i) > Maximum Then Maximum = l(i)
    Next i
End Function

Private Function Minimum(l)
    Dim s1, s2
    Dim i
    s1 = LBound(l)
    s2 = UBound(l)
    Minimum = l(s1)
    For i = s1 To s2
        If l(i) < Minimum Then Minimum = l(i)
    Next i
End Function


© 2019 Better Solutions Limited. All Rights Reserved. © 2019 Better Solutions Limited TopPrevNext