在查找通过对象的属性对VBA中的对象集合进行排序的函数时,我遇到了this sort算法 . 为了确保我理解我实现的代码的所有方面,我想验证我对这个算法的想法 . 对我而言,它看起来像插入排序,但我想与社区核实,以确保我是正确的 .
为了帮助自己更好地理解它,我把这个函数正在做的伪代码放在一起 . (假设它将按升序排序)
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
我已经包含了代码,以防我在上面的伪代码中犯了错误 .
对于那些不熟悉VBA的人,col.Add obj,我将对象插入到集合中对象i之前的集合中 .
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 对于一个永远不会超过300个具有随机置换元素的列表,这个算法是正确的,还是应该尝试实现其他的?
1 回答
我相信这是Selection sort .
Edit: 为了回答你的问题,这不是一个快速的算法,它是一个O(n2),但是,如果这是你唯一的处理,我认为300个元素的O(n2)是好的 .
您应该测试整个程序,然后判断是否需要优化 . 请记住,您的排序算法可以进行优化 .