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!

Sort Array or Collection 1

Status
Not open for further replies.

BlindPete

Programmer
Jul 5, 2000
711
US
Anybody have a function that sorts an array of strings. Or know of a way to sort a collection?
-Pete
 
Choosing the best sort depends on the type of data structure and a host of factors about the data. If the data is nearly always in order then an array of strings can be sorted quite efficiently with a simple bubble sort. However the bubble sort's worst case performance would be if the data was in reverse order. If the data is in a sufficiently random orderthen a quick sort would work better. However a quick sort's worse case is if the data is in order or near order. There are other issues - how long are the strings, is there ancillary data that needs to be moved etc. Anyway here is a simple bubble sort:

Dim iPass, iNdx, iCompVal as Integer
Dim strSwap as String

For iPass = 0 to arySize - 1
For iNdx = 0 to arySize - 1
iCompVal = strComp(aryName(iNdx), aryName(iNdx + 1)
If iCompVal = 1 'returns 1 for str1 > str2
strSwap = aryName(iNdx)
aryName(iNdx) = aryName(iNdx + 1)
aryName(iNdx + 1) = strSwap
End If
Next
Next

I have many other sorting algorithms if this is not helpful

HTH,
JC
 
Thanks JC,

I used a bubble sort which is similar to the one you wrote up there. I even considered (briefly) a bi-directional bubble sort, but my list(s) are so short (<20 recs) that it is hardly needed

For nCount = nRowCount To 1 Step -1
For nInnerCount = 1 To (nCount - 1)
If gList(nInnerCount) > gList(nInnerCount + 1) Then
cTempString = gList(nInnerCount)
gList(nInnerCount) = gList(nInnerCount + 1)
gList(nInnerCount + 1) = cTempString
End If
Next
Next


I am very surpised the VBA does not have more string functions and array sorting built in. I suppose I'm spoiled. Anyway thanks for the info. You should consider posting an FAQ with your sorting routines and pros/cons of each. I scanned the FAQ yesterday and found nothing. Thanks again... and a star for you!
-Pete
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top