简体   繁体   English

如何对二维数组进行排序

[英]How to sort double dimensional array

I have a double dimensional array.我有一个二维数组。 I want to sort the array based on the second column in descending way.我想根据第二列以降序方式对数组进行排序。 Can you please help me你能帮我么

Dim house_rank(12, 1) As Integer
        For h = 1 To 12
            house_rank(h - 1, 0) = h
            house_rank(h - 1, 1) = h_val(h - 1)
        Next

There is no "automatic" way to sort a 2D array.没有“自动”方式对二维数组进行排序。 If you want to do it in place then you would have to implement a sorting algorithm yourself and just do it over the second "column" and, whenever you move a value, perform the same operation on the value in the first "column" as well.如果你想就地做,那么你必须自己实现一个排序算法,然后在第二个“列”上做,每当你移动一个值时,对第一个“列”中的值执行相同的操作出色地。 If you're not determined to do it in place then you can create two 1D arrays and then use the overload of Array.Sort that sorts two arrays based on values in one of them, then repopulate the original array.如果您不确定就地执行此操作,则可以创建两个 1D arrays,然后使用 Array.Sort 的重载,根据其中一个中的值对两个Array.Sort进行排序,然后重新填充原始数组。 Here's a method that will do that:这是一个可以做到这一点的方法:

Private Sub SortBySecondColumn(Of T)(matrix As T(,))
    Dim upperBound = matrix.GetUpperBound(0)
    Dim firstColumn(upperBound) As T
    Dim secondColumn(upperBound) As T

    'Copy data from 2D array to 1D arrays.
    For i = 0 To upperBound
        firstColumn(i) = matrix(i, 0)
        secondColumn(i) = matrix(i, 1)
    Next

    'Sort both columns by the second column.
    Array.Sort(secondColumn, firstColumn)

    'Copy data back from 1D arrays to 2D array.
    For i = 0 To upperBound
        matrix(i, 0) = firstColumn(i)
        matrix(i, 1) = secondColumn(i)
    Next
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM