我想知道如何让这段代码变得更好。我不能让它按升序对关节数组进行排序而不操纵其他2个数组。请帮助
解决方案: 模块模块1
Sub Main()
Dim a() As Integer = {2, 4, 1, 5, 0, 3}
Dim B() As Integer = {10, 8, 6, 9, 7}
Dim value = A.Union(B)
Console.WriteLine("Set A")
Array.Sort(A)
For Each srt As Integer In a
Console.WriteLine("{0}", srt)
Next
Console.WriteLine("set B")
Array.Sort(B)
For Each srt As Integer In B
Console.WriteLine("{0}", srt)
Next
Console.WriteLine("Joining")
For Each c As Integer In value
Console.WriteLine(c)
Next c
Console.ReadKey()
End Sub
结束模块
答案 0 :(得分:1)
据我所知,在线性时间内合并两个排序数组的任务可以通过迭代地决定从哪个数组中取值来完成。我没有Visual Basic的经验,但可以用一些C#-ish伪代码解释这个想法。
int[] A; // first sorted array
int[] B; // second sorted array
int[] C = new int[A.length + B.length]; // will contain the result;
int ia = 0; // index for A
int ib = 0; // index for B
int ic = 0; // index for C
while (ic < c.length) // iterate while C is not filled
{
if (ia == A.length) // A is consumed, must take from B
{
C[ic] = B[ib];
ib = ib + 1;
}
else if (ib == B.length) // B is consumed, must take from A
{
C[ic] = A[ia];
ia = ia + 1;
}
else // neither A nor B is consumed, must make real comparison
{
if (A[ia] < B[ib]) // take from A
{
C[ic] = A[ia];
ia = ia + 1;
}
else // take from B
{
C[ic] = B[ib];
ib = ib + 1;
}
}
ic = ic + 1; // step forward in C
}