Insertion Sort for VB6

Posted On 2018-03-13 by IntelligentSolutionsInc
Tags: VB6 Miscellaneous VB6 Custom Functions 
Views: 36

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

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

    'insert new item

        vAns(lCtr) = vVal
        lNumSorted = lNumSorted + 1

SortedArray = vAns

Exit Function

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

SortedArray = vbEmpty

Exit Function



About the Author

IntelligentSolutionsInc has posted a total of 1 articles.

Comments On This Post

No comments on this post yet!

Do you have a thought relating to this post? You can post your comment here. If you have an unrelated question, you can use the Q&A section to ask it.

Or you can drop a note to the administrators if you're not sure where you should post.

Your IP address is:

Before you can post, you need to prove you are human. If you log in, this test goes away.

Code Links