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 us开发者_JAVA百科e 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?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.
- Lowest of 4, 3, 1 is 1. Add 1 to d, remove from c.
- Lowest of 4, 3, 2 is 2. Add 2 to d, remove from c.
- Lowest of 4, 3, 15 is 3. Add 3 to d, remove from b.
- Lowest of 4, 5, 15 is 4. Add 4 to d, remove from a.
- etc.
Your question is a bit unclear but here goes;
- if you can merge 2 arrays, then 2 merges will merge 3 arrays into 1;
- but it's not difficult to merge 3 arrays in one go either;
- if your arrays are too big to store in memory, you will have to use external sorting algorithms and merge algorithms, Google around and you'll find a ton of material;
- you can certainly merge without sorting, but the result won't be sorted.
If necessary, edit your question and I'll try to be more helpful.
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.
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);
}
}
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.
精彩评论