om Gow is working on a Web page in ASP/VBScript. He's having trouble alphabetically sorting an array with state names. The array in question is loaded with the results of three different queries. The sort is working, but after it's complete, the data in three of the array columns is out of sync. How does he keep all of the rows of data in sync?
Solution #1
Larry Serflaten says the problem is that every time you move one item, you have to move every item in a whole row. However, this works for only small arraysand thus, only with short rows. If the arrays are larger, with several items in a single row, it's undesirable to move that much data aroundif it can be avoided.
One way to avoid this is to use a different array as a pointer (indexing) into the data array. This sorts the data, without having to move it, but it needs to be accessed through the indexing array.
Here's Larry's example code:
HTH
KFS
Private Sub Form_Load()
Dim Data(0 To 1, 0 To 5)
Dim I, J, Index
Randomize
Debug.Print "Original list:"
For i = 0 To 5
J = Int(Rnd * 1000)
Data(0, i) = J
Data(1, i) = "ITEM" & Str(J)
Debug.Print Data(0, i), Data(1, i)
Next
Sort Data, Index
Debug.Print "Sorted:"
For i = 0 To 5
Debug.Print Data(0, Index(i)), Data(1, Index(i)), "was: "; Data(0, i)
Next
End Sub
Sub Sort(ByVal Data, ByRef Index)
Dim p1, p2, pp
ReDim Index(0 To 5) ' Hard coded for demo convenience
For p2 = 0 To 5
Index(p2) = p2
Next
p2 = 1
Do While p1 < 5
Select Case Sgn(Data(0, Index(p2)) - Data(0, Index(p1)))
Case -1
pp = Index(p1)
Index(p1) = Index(p2)
Index(p2) = pp
p2 = p1 + 1
Case 0, 1
p2 = p2 + 1
If p2 > 5 Then
p1 = p1 + 1
p2 = p1 + 1
End If
End Select
Loop
End Sub