This method uses the insertion sort algorithm to sort a numeric array. This algorithm is one of the simplest available, but there are better algorithms (to be posted on this site shortly) for longer lists.
Returns an Array, or vbEmpty if there’s an error e.g., passed array contains elements that can’t be compared to each other, such as objects.
Will work when elements are all numbers or single characters of the same case.
Public Function SortedArray(ByVal NumericArray As Variant) _
As Variant
Dim iStartPoint As Integer, vTemp As Variant
Dim lItem As Long, lCtr As Long, lCtr2 As Long
Dim vVal As Variant
Dim vOrigArray As Variant
Dim vAns As Variant
Dim lNumSorted As Long
Dim lMax As Long
vAns = NumericArray
If Not IsArray(vAns) Then
SortedArray = vbEmpty
Exit Function
End If
On Error GoTo errorhandler
vOrigArray = vAns
iStartPoint = LBound(vAns)
lMax = UBound(vAns) - 1
lNumSorted = 0
For lItem = iStartPoint To lMax
vVal = vOrigArray(lItem + 1)
For lCtr = iStartPoint To lNumSorted
If vAns(lCtr) >= vVal Then Exit For
Next
For lCtr2 = lNumSorted To lCtr Step -1
vAns(lCtr2 + 1) = vAns(lCtr2)
Next
'insert new item
vAns(lCtr) = vVal
lNumSorted = lNumSorted + 1
Next
SortedArray = vAns
Exit Function
'because it's a variant
'people can pass objects or
'other types that can't be
'compared or sorted
errorhandler:
SortedArray = vbEmpty
Exit Function