Insertion Sort for VB6

By | 2018-03-13

This method uses the insertion sort algorithm to sort a numeric array. This algorithm is one of the simplest available, but there are better algorithms (to be posted on this site shortly) for longer lists.

Returns an Array, or vbEmpty if there’s an error e.g., passed array contains elements that can’t be compared to each other, such as objects.

Will work when elements are all numbers or single characters of the same case.

Public Function SortedArray(ByVal NumericArray As Variant) _
As Variant

Dim iStartPoint As Integer, vTemp As Variant
Dim lItem As Long, lCtr As Long, lCtr2 As Long

Dim vVal As Variant
Dim vOrigArray As Variant

Dim vAns As Variant
Dim lNumSorted As Long
Dim lMax As Long

vAns = NumericArray

If Not IsArray(vAns) Then
    SortedArray = vbEmpty
    Exit Function
End If

On Error GoTo errorhandler
vOrigArray = vAns
iStartPoint = LBound(vAns)
lMax = UBound(vAns) - 1

lNumSorted = 0

For lItem = iStartPoint To lMax

    vVal = vOrigArray(lItem + 1)

    For lCtr = iStartPoint To lNumSorted
        If vAns(lCtr) >= vVal Then Exit For
    Next

    For lCtr2 = lNumSorted To lCtr Step -1
        vAns(lCtr2 + 1) = vAns(lCtr2)
    Next

    'insert new item

        vAns(lCtr) = vVal
        lNumSorted = lNumSorted + 1
    Next

SortedArray = vAns

Exit Function

'because it's a variant
'people can pass objects or
'other types that can't be
'compared or sorted

errorhandler:
SortedArray = vbEmpty

Exit Function

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.