Reputation:
suppose that we have three array
int a[]=new int[]{4,6,8,9,11,12};
int b[]=new int[]{3,5,7,13,14};
int c[]=new int[]{1,2,15,16,17};
and we want to merge it into one big d array where d.length=a.length+b.length+c.length
but we have memory problem it means that we must need use only this d array where we should merge these these three array of course we can use merge sort but can we use merge algorithm without sorting method? like two sorted array we can merge in one sorted array what about three or more array?
Upvotes: 0
Views: 271
Reputation: 700312
If you just want to concatenate the arrays, you can create the target array and copy the data into it:
int[] d = new int[a.Length + b.Length + c.Length];
a.CopyTo(d, 0);
b.CopyTo(d, a.Length);
c.CopyTo(d, a.Length + b.Length);
This will have a minimum of overhead, as only the size needed is allocated. If you for example add the items to a List<int>
, it will allocate larger and larger arrays as it grows, and the final capacity will be larger than needed.
Upvotes: 0
Reputation: 10713
Possibly try this:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int a[]=new int[]{4,6,8,9,11,12};
int b[]=new int[]{3,5,7,13,14};
int c[]=new int[]{1,2,15,16,17};
foreach (int element in a)
{
Console.WriteLine(element);
}
foreach (int element in b)
{
Console.WriteLine(element);
}
foreach (int element in c)
{
Console.WriteLine(element);
}
var list = new List<int>();
list.AddRange(a);
list.AddRange(b);
list.AddRange(c);
int[] d = list.ToArray();
foreach (int element in d)
{
Console.WriteLine(element);
}
}
Upvotes: 0
Reputation: 75598
Merge sort works just as well with 3 or more arrays. To build d, keep adding the lowest value at the start of a, b and c. Remove that element, repeat.
Upvotes: 2
Reputation: 78316
Your question is a bit unclear but here goes;
If necessary, edit your question and I'll try to be more helpful.
Upvotes: 0
Reputation: 54005
You mean place them all in one array in ascending order?
You can just copy them all and then bubblesort or insertsort.
If they are ordered, you can use the same merge algorithm that is used in mergesort. You will need an index pointer for each array. In each step, select minimum of all arrays at their respective indexes, insert it to the destination table, and increase source array's index.
Upvotes: 0