2016-03-08 326 views
0

我想知道如何让这段代码更好。我不能得到它来按升序排列联合数组而不操纵其他2个数组。麻烦协助给定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

那究竟是什么问题呢? – Mureinik

+0

如果我要从他们的数组中切换说3和7,联合数组将不会按升序排序,或者如果我在这两个数组中都放置随机数,结果将不会被排序 – snash

+0

“联合”执行某种排序吗?据我的理解,输出不会被排序。 – Codor

回答

1

我的理解,合并在线性时间两个已排序的阵列的任务可以通过迭代地决定从哪个数组的值是做要采取。我没有使用Visual Basic的经验,但可以用一些C#伪代码解释这个想法。

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 
}