简体   繁体   中英

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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