Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting elements of an array

Status
Not open for further replies.

Thorny

Programmer
Jul 2, 2001
23
GB
I am trying to sort the elements of an array but am not having much success. I am trying to sort a list of numbers from smallest to largest. Please help.
 
There are a few questions. And several answers.

Being somewhat contray, I will start w/ answers.

[tab]There have been MANY threads on sorting in these (Ms. Access) forums as well as the VB forums. Do a keyword search on "sort" and you will get a lot of guidance/advice.

[tab]An excellent approach (IMHO) to sorting simplistic values is to just create a recordset of the values and let your favioite db engine do the work.

[tab]A VERY simplistic sort simply keeps comparing a current element of the data elements with the next item in the list. If they are not properly ordered, swap them. In a simple loop, set a flag at the start, walk through the ordered pairs with the compare thinngggyyyy. If they pair is "disorderly" (never mind DRUNK!) then "Order" them (to behave?) and set the flag thinngggyyyy false. At the end of the loop, check the flag and exit only when it remains "true". Otherwise walk the dataset again (looking for the disorderly ones).

The following IS NOT recommended for production purposes, however it may offer some insight to some specific problem you are having:

Code:
Public Function basSimpleSort(ArrayIn As Variant) As Variant

    Dim Idx As Integer
    Dim SortFlg As Boolean
    Dim Sorted As Boolean
    Dim ArrayOut() As Variant

    ReDim Preserve ArrayOut(UBound(ArrayIn))

    For Idx = 0 To UBound(ArrayIn)
        ArrayOut(Idx) = ArrayIn(Idx)
    Next Idx

    Do While Not Sorted
        For Idx = 0 To UBound(ArrayOut) - 1
            If (ArrayOut(Idx) < ArrayOut(Idx + 1)) Then
                varTemp = ArrayOut(Idx)
                ArrayOut(Idx) = ArrayOut(Idx + 1)
                ArrayOut(Idx + 1) = varTemp
                SortFlg = False
            End If
        Next Idx
        If (SortFlg) Then
            Sorted = True
        End If
        SortFlg = True
    Loop

    basSimpleSort = ArrayOut

End Function

MichaelRed
mred@att.net

There is never time to do it right but there is always time to do it over
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top