PDA

View Full Version : Solved: Optimal Array Sort



jamescol
07-11-2004, 07:59 PM
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.


Option Base 1

Dim arrayContacts() As Variant

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

Jacob Hilderbrand
07-11-2004, 09:00 PM
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:


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

mark007
07-12-2004, 01:19 AM
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

:)

jamescol
07-20-2004, 11:07 PM
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