![]() |
|
|
| |
|
||||
The general merge algorithm has a set of pointers p0..n that point to positions in a set of lists L0..n. Initially they point to the first item in each list. The algorithm is as follows: While any of p0..n still point to data inside of L0..n instead of past the end:
AnalysisMerge algorithms generally run in time proportional to the sum of the lengths of the lists; merge algorithms that operate on large numbers of lists at once will multiply the sum of the lengths of the lists by the time to figure out which of the pointers points to the lowest item, which can be accomplished with a heap-based priority queue in O(lg n) time, for O(m lg n) time (where m is the sum of the lengths of the lists, and lg is log base 2). The classic merge (the one used in merge sort) outputs the data item with the lowest key at each step; given some sorted lists, it produces a sorted list containing all the elements in any of the input lists, and it does so in time proportional to the sum of the lengths of the input lists. UsesMerge can also be used for a variety of other things:
Sample implementations
Haskellmerge :: Ord a => [a]->[a]->[a] merge a [] = a merge [] b = b merge (a:as) (b:bs) | a <= b = a : merge as (b:bs) | otherwise = b : merge (a:as) bs Python
def merge(a, b): if len(a) == 0: return b if len(b) == 0: return a if a[0] <= b[0]: return a[0:1] + merge(a[1:], b) else: return b[0:1] + merge(a, b[1:]) C / C++
void Merge(float v[], int start, int mid, int end)
{
int i, j, k;
float* tmp = malloc(sizeof(float) * (end - start));
i = start;
j = mid;
k = 0;
while ((i < mid) && (j < end))
{
if (v[i] <= v[j])
tmp[k++] = v[i++];
else
tmp[k++] = v[j++];
}
while (i < mid)
tmp[k++] = v[i++];
while (j < end)
tmp[k++] = v[j++];
for (i = 0; i < (end-start); i++)
v[start+i] = tmp[i];
free(tmp);
}
Java
void Merge(float[] array, int start, int mid, int end)
{
int i = start;
int j = mid;
int k = 0;
float[] temp = new float[end - start];
while ((i < mid) && j < end))
if (array[i] <= array[j])
temp[k++] = array[i++];
else
temp[k++] = array[j++];
while (i < mid)
temp[k++] = array[i++];
while (j < end)
temp[k++] = array[j++];
for (i = start; i < end; i++)
array[i] = temp[i - start];
}
|
|
|
|
|
|
|
|
Copyright 2008 WordIQ.com - Privacy Policy
::
Terms of Use
:: Contact Us
:: About Us This article is licensed under the GNU Free Documentation License. It uses material from the Wikipedia article "Merge algorithm". |