要对多维数组进行排序,您可以使用与对单维数组进行排序完全相同的过程。
你循环遍历数组,如果两个相邻的成员的顺序错误,那么你将它们左右交换。
想象一下,您有一个多维数组,例如
Dim Array(12, 4) String
因此,例如,假设您想按最后一列对数组进行排序。
For index1 = 0 to Array.length - 1
For index2 = 0 to Array.length - 2
If Array(index2, 4) > Array(index2 + 1, 4) Then
// this sorts the last column
Temp4 = Array(index2, 4)
Array(index2, 4) = Array(index2 + 1, 4)
Array(index2 + 1, 4) = Temp4
// and we repeat this swopping pattern for each of the other columns, so they are all sorted in the same way
Temp3 = Array(index2, 3)
Array(index2, 3) = Array(index2 + 1, 3)
Array(index2 + 1, 3) = Temp3
Temp2 = Array(index2, 2)
Array(index2, 2) = Array(index2 + 1, 2)
Array(index2 + 1, 2) = Temp2
Temp1 = Array(index2, 1)
Array(index2, 1) = Array(index2 + 1, 1)
Array(index2 + 1, 1) = Temp1
Temp0 = Array(index2, 0)
Array(index2, 0) = Array(index2 + 1, 0)
Array(index2 + 1, 0) = Temp0
Next
Next
所以现在所有的列都按最后一列排序。
您可能想知道如果 4 列是字符串而一列是数字,如何排序,并假设您想按数字列排序。
你可以这样做
For index1 = 0 to Array.length - 1
For index2 = 0 to Array.length - 2
If CSng(Array(index2, 4)) > CSng(Array(index2 + 1, 4)) Then
// this sorts the last column
Temp4 = Array(index2, 4)
Array(index2, 4) = Array(index2 + 1, 4)
Array(index2 + 1, 4) = Temp4
// and we repeat this swopping pattern for each of the other columns, so they are all sorted in the same way
Temp3 = Array(index2, 3)
Array(index2, 3) = Array(index2 + 1, 3)
Array(index2 + 1, 3) = Temp3
Temp2 = Array(index2, 2)
Array(index2, 2) = Array(index2 + 1, 2)
Array(index2 + 1, 2) = Temp2
Temp1 = Array(index2, 1)
Array(index2, 1) = Array(index2 + 1, 1)
Array(index2 + 1, 1) = Temp1
Temp0 = Array(index2, 0)
Array(index2, 0) = Array(index2 + 1, 0)
Array(index2 + 1, 0) = Temp0
Next
Next
我所做的只是将 Datatype 转换为从 String 到 Single 的最后一列,然后像以前一样比较相邻的值。
所以这是对多维数组进行排序的一种非常基本的方法,它也适用于包含字符串和数字的混合数组。