Visual Basic for Applications/冒泡排序一维数组
外观
本页讨论的是对一维数组的排序。这些通常用于将列表放入具有Array方法的变体中。在VBA中找到这样的排序例程比较少见,因为大多数排序是在二维中进行的。
- 过程BubbleSort1DArray()使用最慢的排序方法。但是,这里这样做似乎没有缺点,因为很少有列表能达到很大的尺寸。有升序或降序排序选项,以及返回方法。如果提供了一个返回数组,它将被使用,否则将通过在其中返回来更改输入数组。
Function BubbleSort1DArray(vIn As Variant, bAscending As Boolean, Optional vRet As Variant) As Boolean
' Sorts the single dimension list array, ascending or descending
' Returns sorted list in vRet if supplied, otherwise in vIn modified
Dim First As Long, Last As Long
Dim i As Long, j As Long, bWasMissing As Boolean
Dim Temp As Variant, vW As Variant
First = LBound(vIn)
Last = UBound(vIn)
ReDim vW(First To Last, 1)
vW = vIn
If bAscending = True Then
For i = First To Last - 1
For j = i + 1 To Last
If vW(i) > vW(j) Then
Temp = vW(j)
vW(j) = vW(i)
vW(i) = Temp
End If
Next j
Next i
Else 'descending sort
For i = First To Last - 1
For j = i + 1 To Last
If vW(i) < vW(j) Then
Temp = vW(j)
vW(j) = vW(i)
vW(i) = Temp
End If
Next j
Next i
End If
'find whether optional vRet was initially missing
bWasMissing = IsMissing(vRet)
'transfers
If bWasMissing Then
vIn = vW 'return in input array
Else
ReDim vRet(First To Last, 1)
vRet = vW 'return with input unchanged
End If
BubbleSort1DArray = True
End Function