我有两个这样的数组:
name(0)="jack"
name(1)="nicho"
name(2)="Han"
name(3)="Hugo"
Value(0)="70"
Value(1)="60"
Value(2)="30"
Value(3)="90"
如何排序"名称"基于"价值"排序位置结果
我想要的结果:
Value(0)="90"
Value(1)="70"
Value(2)="60"
Value(3)="30"
name(0)="Hugo"
name(1)="jack"
name(2)="nicho"
name(3)="Han"
答案 0 :(得分:1)
使用Dictionary比使用两个单独的数组
更容易Dim val As New Dictionary(Of String, String)
val.Add("jack", 70)
val.Add("nicho", 60)
val.Add("Han", 30)
val.Add("Hugo", 90)
你可以按照下面的方式对其进行排序
Dim sorted = From item In val Order By item.Value Descending Select item
如果要添加已排序到数组
Dim arrName(), arrValue() As String
Dim k As Integer = 0
ReDim Preserve arrName(sorted.Count - 1)
ReDim Preserve arrValue(sorted.Count - 1)
For Each it In sorted
arrName(k) = it.Key
arrValue(k) = it.Value
k = k + 1
Next
或
你可以这样做
Dim name() As String = {"jack", "nicho", "Han", "Hugo"}
Dim value() As String = {"70", "60", "30", "90"}
Dim j As Integer = 0
Dim new_value = From val1 In value Order By val1 Descending Select val1
Dim new_name() As String
Dim idx As Integer
ReDim Preserve new_name(new_value.Count - 1)
For Each itm In new_value
idx = Array.IndexOf(value, itm)
new_name(j) = name(idx)
j = j + 1
Next
这将创建2个具有所需排序顺序的value
和name
新数组
答案 1 :(得分:0)
生成一个索引数组值,然后根据值对这些索引进行排序。然后根据排序的索引重新排序值和名称。此示例使用带有lambda compare的sort。对时间复杂度的重新排序是线性O(n),因为每个数组存储器将元素放置在其排序顺序中。 index()将恢复为0到length-1。
Module Module1
Sub Main()
Dim name() As String = {"jack", "nicho", "han", "hugo"}
Dim value() As String = {"70", "60", "30", "90"}
Dim index(name.Length - 1) As Integer
Dim i, j, k As Integer
Dim tname, tvalue As String
'initialize index
For i = 0 To name.Length - 1
index(i) = i
Next
'reverse sort index according to value (compare y,x)
Array.Sort(index, Function(x As Object, y As Object) String.Compare(value(y), value(x)))
'reorder value and name in place using sorted index
For i = 0 To name.Length - 1
If i <> index(i) Then
tvalue = value(i)
tname = name(i)
k = i
j = index(k)
While i <> j
value(k) = value(j)
name(k) = name(j)
index(k) = k
k = j
j = index(k)
End While
value(k) = tvalue
name(k) = tname
index(k) = k
End If
Next
For i = 0 To name.Length - 1
Console.WriteLine(name(i) + ControlChars.Tab + value(i))
Next
End Sub
End Module