要排序多维数组,可以使用与排序单维数组完全相同的过程。
您循环遍历数组,如果两个相邻成员的顺序错误,那么您将它们翻转过来。
假设你有一个多维数组如
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
我所做的是把数据类型从字符串转换为最后一列单,然后根据之前相邻的值进行比较。
所以这是一个排序多维数组的非常基本的方法,它也适用于包含字符串和数字的混合数组。
为什么不能使用['Array.Sort'](http://msdn.microsoft.com/en-us/library/system.array.sort(v = vs.110).aspx)? –
任务是做一个排序功能.. –
请看这里http://en.wikipedia.org/wiki/Bubble_sort – Teejay