Click to See Complete Forum and Search --> : Anyone know if there is a way to Sort an Array in VBScript?


gangelo
July 9th, 2002, 01:16 PM
Anyone know if there is a way to Sort an Array in VBScript?

BroncoFan
July 12th, 2002, 07:48 AM
Why not use a quick sort algorithm? You can do a search on that on google or whatever. "A Visual Basic 6 Programmer's Toolkit" by Hank Marquis and Eric Smith has that and a whole host of other practical algorithms for Visual Basic.

Surrendermonkey
July 12th, 2002, 11:09 AM
This "Function" ( - it should really be a sub note byRef array parameter) sort an array of integers (with initial index =1).

It needs a bit of tidying up, but there's no reason it couldn't be expanded to sort string arrays too.

Function arrOrderThis(ByRef intArr())

' I believe this is called a "Shell Sort"
Dim tmpindx
Dim team1(), team2()
Dim tmpArr()
Redim tmpArr(UBound(intArr))
for tmpindx = 1 to UBound(intArr)
tmpArr(tmpindx) = intArr(tmpIndx)
next
ReDim team1(UBound(tmpArr))
ReDim team2(UBound(tmpArr))
Dim gap, doneflag
Dim index, swap1, swap2

'Gap starts as half the records
gap = Int(UBound(tmpArr) / 2)
Do While gap >= 1
Do
doneflag = 1
For index = 1 To UBound(tmpArr) - gap

If clng(tmpArr(index)) > clng(tmpArr(index + gap)) Then
swap1 = clng(tmpArr(index))
swap2 = clng(team1(index))
tmpArr(index) = clng(tmpArr(index + gap))
team1(index) = clng(team1(index + gap))
tmpArr(index + gap) = clng(swap1)
team1(index + gap) = clng(swap2)
doneflag = 0
End If
Next
Loop Until doneflag = 1
gap = Int(gap / 2)
Loop
for Index = 1 to UBound(intArr)
intArr(Index) = tmpArr(Index)
next

End Function

See how you go.

Rezner
July 16th, 2002, 10:07 PM
Use the good old fashioned Bubble Sort:Dim a() as integer
Dim i as integer
Dim j as integer
Dim k as integer
Const n = 1000

'---------------------------------
'Test array
Redim a(0 to n-1)
for i = 0 to n-1
a(i) = Int((1000 * Rnd) + 1) ' random # between 1 and 1000
next i
'----------------------------------

For i = 0 To n - 1
For j = 0 To n - 1
If a(i) < a(j) Then
k = a(i)
a(i) = a(j)
a(j) = k
End If
Next j
Next i

Surrendermonkey
July 18th, 2002, 03:53 AM
...only you're not going to need those types in the Dim statements in vbscript, nor the index after the "next" statements.
I don't know for sure, but I don't think you'll get away with Redim (0 to..) either.