I came across this sort algorithm when looking for a function to sort a collection of objects in VBA by a property of the object. In order to make sure that I understand all aspects of the code that I implement, I wanted to validate my thoughts on this algorithm. To me it looks like an Insertion Sort, but I wanted to check with the community to make sure that I was correct.
To help myself understand it better, I put together this pseudocode of what I believe that the function is doing. (Just assume it will be sorted in ascending order)
UnknownSort(collection C)
for i=1 to C.Count - 1
begin
x = C[i].Value
index = i
for j=i+1 to C.Count
begin
y = C[j].Value
if x > y then
x = y
index = j
j++
end
if index <> i then
temp = C[index]
C.Remove(index)
C.Add temp before C[i]
i = i + 1
end
I have included the code as well in case I made a mistake in the pseudocode above.
For those not familiar with VBA, the col.Add obj, , i inserts the object into the collection before the object i in the collection.
Private Function SortCollection(col As Collection, psSortPropertyName As String, pbAscending As Boolean) As Collection
Dim obj As Object
Dim i As Integer
Dim j As Integer
Dim iMinMaxIndex As Integer
Dim vMinMax As Variant
Dim vValue As Variant
Dim bSortCondition As Boolean
Dim bUseKey As Boolean
Dim sKey As String
For i = 1 To col.Count - 1
Set obj = col(i)
vMinMax = CallByName(obj, psSortPropertyName, VbGet)
iMinMaxIndex = i
For j = i + 1 To col.Count
Set obj = col(j)
vValue = CallByName(obj, psSortPropertyName, VbGet)
If (pbAscending) Then
bSortCondition = (vValue < vMinMax)
Else
bSortCondition = (vValue > vMinMax)
End If
If (bSortCondition) Then
vMinMax = vValue
iMinMaxIndex = j
End If
Set obj = Nothing
Next j
If (iMinMaxIndex <> i) Then
Set obj = col(iMinMaxIndex)
col.Remove iMinMaxIndex
col.Add obj, , i
Set obj = Nothing
End If
Set obj = Nothing
Next i
Set SortCollection = col
End Function
Edit For a list that will never be longer than 300 elements with a random displacment, is this algorithm ok, or should I try to implement something else?