Insertion Sort


Public Sub InsertionSort(ByRef arr() As Double) 
Dim i As Long
Dim j As Long

    For i = 1 To UBound(arr)
        j = i
        Do While (j > 0)
            If (arr(j - 1) > arr(j)) Then
                Call Swap_Values(arr, j, j - 1)
                j = j - 1
            Else
                Exit Do
            End If
        Loop
    Next i
End Sub
 
Private Sub Swap_Values(ByRef arr() As Double, _
                        ByVal i1 As Long, _
                        ByVal i2 As Long)
 
Dim buffer As Double
 
    buffer = arr(i1)
    arr(i1) = arr(i2)
    arr(i2) = buffer
End Sub

This one is faster.

Public Sub InsertionSort2(ByRef arr() As Double) 
Dim i As Long
Dim j As Long
Dim buffer As Double
 
    For i = 1 To UBound(arr)
        buffer = arr(i)
        j = i - 1
        Do Until (j < 0)
            If (arr(j) > buffer) Then
                arr(j + 1) = arr(j)
                j = j - 1
            Else
                Exit Do
            End If
        Loop
 
        arr(j + 1) = buffer
    Next i
End Sub

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