Merge algorithm



         



Merge algorithms are a family of algorithms that run sequentially over multiple sorted lists, typically producing more sorted lists as output. This is well-suited for machines with tape drives. Use has declined due to large random access memories, and many applications of merge algorithms have faster alternatives when you have a random-access memory that holds all your data.

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:

  1. do something with the data items p0..n point to in their respective lists
  2. find out which of those pointers points to the item with the lowest key; advance one of those pointers to the next item in its list
[Top]

Analysis

Merge 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.

[Top]

Uses

Merge can also be used for a variety of other things:


[Top]

Sample implementations

[Top]

FL

merge
[Top]

Haskell

merge :: 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
[Top]

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:])
[Top]

C

void merge (float v[], int start, int mid, int end) { int v1_n, v2_n, v1_index, v2_index, i; v1_n = mid - start; v2_n = end - mid; float v1[v1_n]; float v2[v2_n]; for (i=0; i<v1_n; i++) v1[i] = v[start + i]; for (i=0; i<v2_n; i++) v2[i] = v[mid + i]; v1_index = 0; v2_index = 0; for (i=0; (v1_index < v1_n) && (v2_index < v2_n); i++) { if (v1[v1_index] <= v2[v2_index]) v[start + i] = v1[v1_index++]; else v[start + i] = v2[v2_index++]; } for (; v1_index < v1_n; i++) v[start + i] = v1[v1_index++]; for (; v2_index < v2_n; i++) v[start + i] = v2[v2_index++]; }




  View Live Article   This article is from Wikipedia. All text is available under the terms of the GNU Free Documentation License