What is the simplest way to sort items in an array in alphabetical order?
Printable View
What is the simplest way to sort items in an array in alphabetical order?
With a ListBox List1.Sorted=True List1.Visible = False
Works for up to 32767 elements.Code:
Dim i,j
For i = 0 to Ubound(arr)
List1.AddItem arr(i)
next
for i = 0 to List1.ListCount - 1
arr(i) = List1.List(i)
next
That's simple but slow with larger (>1000) arrays. There's bubble sort, selection sort, the all-powerful and speedy merge sort.... But if you only have a few dozen elements, then the linear sort (what Jim suggested) is fine.
For smaller arrays here is a fairly simple way
Of course for large arrays you would want something faster.Code:Dim arrNames(5) As String
Private Sub Command1_Click()
For i = 0 To 4
MsgBox "Names before sort.... " & vbCrLf & arrNames(i)
Next i
SortStringArray arrNames(), True, False
For i = 0 To 4
MsgBox "Names after sort.... " & vbCrLf & arrNames(i)
Next i
End Sub
Private Sub Form_Load()
arrNames(0) = "Steven"
arrNames(1) = "John"
arrNames(2) = "Mark"
arrNames(3) = "Rob"
arrNames(4) = "Chuck"
End Sub
Public Sub SortStringArray(MyArray() As String, _
Optional ByVal bAscending As Boolean = True, _
Optional ByVal bCaseSensitive As Boolean = False)
Dim lMin As Long
Dim lMax As Long
Dim lOrder As Long
Dim lCompareType As Long
lMin = LBound(MyArray)
lMax = UBound(MyArray) - 1
If lMin = lMax Then
Exit Sub
End If
' Set Asc or Dsc Order
lOrder = IIf(bAscending, 1, -1)
' Set Case Sensitive
lCompareType = IIf(bCaseSensitive, vbBinaryCompare, vbTextCompare)
Dim sValue As String
Dim lCnt1 As Long
Dim lCnt2 As Long
' Loop through array move elements down to their correct place
For lCount1 = lMin + 1 To lMax
sValue = MyArray(lCount1)
' Find the place to put it
For lCount2 = lCount1 - 1 To lMin Step -1
If StrComp(MyArray(lCount2), sValue, lCompareType) <> lOrder Then
Exit For
End If
MyArray(lCount2 + 1) = MyArray(lCount2)
Next lCount2
' Insert it
MyArray(lCount2 + 1) = sValue
Next
End Sub
what ever happened to the best there ever was and still is....quick sort?
I think I've heard of it, but that it is only really speedy the larger the array. Can you give us a pseudocode algorithm for how it works again?
Here is an example of Quick Sort, courtesy of the VB2TheMax site
http://www.vb2themax.com/Item.asp?PageID=CodeBank&ID=77
FYI, you can't click on his link, but mine works :) http://www.vb2themax.com/Item.asp?PageID=CodeBank&ID=77
Here is an excellent article from one of the true masters of VB,
Francesco Balena
It shows many different sorting methods.
http://www.vb2themax.com/HtmlDoc.asp...Articles&ID=10
I could click on the link in previous mention from myself?????
This last one is screwed up too. It tries to open http:/// which obviously doesn't exist. If you're using the [ url ] and [ /url ] tags, don't. :)
Oops, sorry
I pasted the link into the Text part, my mistake