Bubble Sort

Bubble Sort uses a 'swapping' strategy to repeatedly swap the adjacent elements if they are in wrong order.

Sub TestSort() 
Dim avTesting() As Variant
   avTesting = Array(45, 30, 25, 15, 10, 5, 40, 20, 35, 50)
   Call Array_BubbleSort(avTesting)
   Stop
End Sub
Public Sub Array_BubbleSort(ByRef vArrayName As Variant, _ 
                   Optional ByVal lUpper As Long = -1, _
                   Optional ByVal lLower As Long = -1)

Dim vtemp As Variant
Dim i As Long
Dim j As Long

   If IsEmpty(vArrayName) = True Then Exit Sub
   If lLower = -1 Then lLower = LBound(vArrayName, 1)
   If lUpper = -1 Then lUpper = UBound(vArrayName, 1)

   For i = lLower To (lUpper - 1)
      For j = i To lUpper
         If (vArrayName(j) < vArrayName(i)) Then
            vtemp = vArrayName(i)
            vArrayName(i) = vArrayName(j)
            vArrayName(j) = vtemp
         End If
      Next j
   Next i
End Sub

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