Consulting

Results 1 to 4 of 4

Thread: Solved: Optimal Array Sort

  1. #1
    VBAX Tutor jamescol's Avatar
    Joined
    May 2004
    Location
    Charlotte, NC
    Posts
    251
    Location

    Solved: Optimal Array Sort

    What is the optimal way to sort an array containing names alphabetically in ascending order? Here is an example of the array I am using.

    [vba]
    Option Base 1

    Dim arrayContacts() As Variant

    arrayContacts = Array("James", "Mary", "Tom", "Beth", "Bob", "Chris", "Daniel", "Lari", "Al", "Teresa")
    [/vba]
    "All that's necessary for evil to triumph is for good men to do nothing."

  2. #2
    Site Admin
    Jedi Master
    VBAX Guru Jacob Hilderbrand's Avatar
    Joined
    Jun 2004
    Location
    Roseville, CA
    Posts
    3,712
    Location
    You could use what is called a bubble sort where you compare two items in the array at a time and switch them to be in order, problem is that it is slow. If you are dealing with many items could take a while.

    Try this:

    [vba]
    Option Base 1
    Option Explicit
    Sub test()
    Dim arrayContacts() As Variant

    arrayContacts = Array("James", "Mary", "Tom", "Beth", "Bob", "Chris", _
    "Daniel", "Lari", "Al", "Teresa")
    Call BubbleSort(arrayContacts)


    End Sub
    Sub BubbleSort(MyArray() As Variant)
    Dim First As Integer
    Dim Last As Integer
    Dim i As Integer
    Dim j As Integer
    Dim Temp As String
    Dim List As String
    First = LBound(MyArray)
    Last = UBound(MyArray)
    For i = First To Last - 1
    For j = i + 1 To Last
    If MyArray(i) > MyArray(j) Then
    Temp = MyArray(j)
    MyArray(j) = MyArray(i)
    MyArray(i) = Temp
    End If
    Next j
    Next i
    For i = 1 To UBound(MyArray)
    List = List & vbCrLf & MyArray(i)
    Next
    MsgBox List
    End Sub
    [/vba]

  3. #3
    BoardCoder
    Licensed Coder VBAX Expert mark007's Avatar
    Joined
    May 2004
    Location
    Leeds, UK
    Posts
    622
    Location
    As Jake said the bubble sort is the easiest to follow and for that reason the most used. If you have large amounts of data though another sort method may be appropriate. For an excellent discussion of pretty much all sorting methods see:

    http://www.visualbasicforum.com/showthread.php?t=78889

    "Computers are useless. They can only give you answers." - Pablo Picasso
    Mark Rowlinson FIA | The Code Net

  4. #4
    VBAX Tutor jamescol's Avatar
    Joined
    May 2004
    Location
    Charlotte, NC
    Posts
    251
    Location
    Thanks for the suggestions. Jacob's came closest to what I needed to do, and I was able to modify his sample to resolve my question.

    Cheers,
    James
    "All that's necessary for evil to triumph is for good men to do nothing."

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •