Search Tools Links Login

Insertion Sort for VB6


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

 

 

About this post

Posted: 2018-03-13
By: IntelligentSolutionsInc
Viewed: 1,290 times

Categories

Visual Basic 6

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.