Merge 2 sorted Array in C#

using System;
using System.Linq;

namespace Merge2Array
{
class Program
{
static void Main()
{
int[] A = { 0, 3, 5, 6, 9, 10, 13, 14 }; // already sorted
int[] B = { 1, 2, 4, 6, 7, 11, 12, 15, 16 }; // ditto

// create sufficiently large output array
int[] C = new int[A.Length + B.Length];

// create indices to keep track of positions in B and C
int indexB = 0, indexC = 0;

// iterate through A
for (int i = 0; i < A.Length; i++)
{
// iterate through B ignoring elements already added to C
for (int j = indexB; j < B.Length; j++)
{
// if B contains elements which are smaller than the current element of A, add them to C
if (B[j] < A[i])
{
C[indexC++] = B[j];
indexB = j + 1; // value at which to start next iteration of B
}
else
{
// stop iterating when there are no more elements of B smaller than current element of A
break;
}
}
// now add current element of A to C
C[indexC++] = A[i];
// if this is A's final element but there are still larger items of B, add them to C
if (i == A.Length - 1 && indexB < B.Length)
{
for (int k = indexB; k < B.Length; k++) C[indexC++] = B[k];
}
}

// check it worked
for (int i = 0; i < C.Length; i++) Console.Write("{0} ", C[i]);
Console.WriteLine();

// Test do the same way by LINQ
int[] D = A.Concat(B).OrderBy(n => n).ToArray();

// check it worked again
for (int i = 0; i < D.Length; i++) Console.Write("{0} ", D[i]);
Console.WriteLine();

Console.ReadKey();
}
}
}



Advertisements