Jump to content

User:ParAlgMergeSort/sandbox/Parallel merge sort

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by ParAlgMergeSort (talk | contribs) at 11:04, 5 February 2020 (Parallel merge sort). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Parallel merge sort

Merge sort parallelizes well due to the use of the divide-and-conquer method. Many different parallel variants of the algorithm have been developed over the years.

Simple approach

A first approach is the parallelization of recursive calls, as described in the following pseudocode (see also fork and join):

// Sort elements lo through hi (exclusive) of array A.
algorithm mergesort(A, lo, hi) is
    if lo+1 < hi then  // Two or more elements.
        mid := ⌊(lo + hi) / 2⌋
        fork mergesort(A, lo, mid)
        mergesort(A, mid, hi)
        join
        merge(A, lo, mid, hi)

This Algorithm is the trivial modification of the sequential version, and does not parallelize well. Therefore its speedup is not very impressive. It has a span of , which is only an improvement of compared to the sequential version (see Introduction to Algorithms). This is mainly due to the sequential merge method, as it is the bottleneck of the parallel executions.

Parallelizing the merge method

Better parallelism can be achieved by using a parallel merge algorithm. Cormen et al.[1] present a binary variant that merges two sorted sub-sequences into one sorted output sequence.

In one of the sequences (the longer one if unequal length), the element of the middle index is selected. Its position in the other sequence is determined, so that this sequence would remain sorted if this element were inserted at this position. Thus one knows how many other elements from both sequences are smaller and the position of the selected element in the output sequence can be calculated. For the partial sequences of the smaller and larger elements created in this way, the merge algorithm is again executed in parallel until the base case of the recursion is reached.

The following pseudocode shows the modified parallel merge sort method using the parallel merge algorithm (adopted from Cormen et al.)

/**
 * A: Input array
 * B: Output array
 * lo: lower bound
 * hi: higher bound
 * off: offset
 */
algorithm PMergesort(A, lo, hi, B, off) is
    len := hi - lo + 1
    if len == 1
        B[off] := A[lo]
    else let T[1..len] be a new array
        mid := ⌊(lo + hi) / 2⌋ 
        mid' := mid - lo + 1
        fork PMergesort(A, lo, mid, T, 1)
        PMergesort(A, mid + 1, hi, T, mid' + 1) 
        join 
        PMerge(T, 1, mid', mid' + 1, len, B, off)

In order to analyze a Recurrence relation for the worst case span, the recursive calls of PMergesort have to be incorporated only once due to their parallel execution, obtaining

.

For detailed information about the complexity of the parallel merge procedure, see Merge algorithm.

The solution of this recurrence is given by

.

This parallel merge algorithm reaches a parallelism of , which is much higher than the parallelism of the naive algorithm.

Parallel multiway merge sort

K-way merge is a generalization of 2-way merge, or binary merge, in which k sorted sequences are merged together. This merge variant is well suited to describe a sorting algorithm on a PRAM[2][3].

Basic Idea

The parallel multiway mergesort process on four processors to .

Given an unsorted sequence of elements, the goal is to sort the sequence with available processors. These elements are distributed equally among all processors and sorted locally using a sequential Sorting algorithm. Hence, the sequence consists of sorted sequences of length . For simplification let n be a multiple of p, so that for .

These sequences will be used to perform a splitter selection. For , the algorithm determines splitter elements with global rank .

Then the corresponding positions of in each sequence are determined with binary search and thus the are further partitioned into subsequences with .

Furthermore the elements of are assigned to processor , means all elements between rank and rank , which are distributed over all . Thus each processor receives a sequence of sorted sequences.

The fact that the rank of the splitter elements was chosen globally, provides two important properties: On the one hand, was chosen so that each processor can still operate on elements after assignment. The Algorithm is perfectly load-balanced. On the other hand, all elements on processor are less than or equal to all elements on processor .

Hence, each processor performs the p-way merge locally and thus obtains a sorted sequence from its sub-sequences. Because of the second property, no further p-way-merge has to be performed, the results only have to be put together in the order of the processor number.

Splitter selection

In its simplest form, given sorted sequences distributed evenly on processors and a rank , the task is to find an element with a global rank in the union of the sequences. Hence, this can be used to divide each in two parts at a splitter index , where the lower part contains only elements which are smaller than , while the elements bigger than are located in the upper part.

The presented algorithm returns the indices of the splits in each sequence, e.g. the indices in sequences such that has a global rank less than and .

msSelect(S: Array of sorted Sequences [S_1,..,S_p], k: int)	returns Array of int
	for i = 1,..., p: 
	    (l_i, r_i) = (0, |S_i|-1)
	while there exists i: l_i < r_i:
		//pick Pivot Element in S_j[l_j],..,S_j[r_j], chose random j uniformly
		v := pickPivot(S, l, r)
		for i = 1,..,p:
			m_i = binarySearch(v, S_i[l_i, r_i]) //sequentially
		if m_1 + ... + m_p >= k: 
			r := m  //vector assignment
		else:
			l := m 
	return l

For the complexity analysis the PRAM model is chosen.

If the data is evenly distributed over all , the p-fold execution of the binarySearch method has a running time of . The expected recursion depth is as in the ordinary Quickselect.

Thus the overall expected running time is .

Applied on the parallel multiway merge sort, this algorithm has to be invoked in parallel such that all splitter elements of rank for are found simultaneously. These splitter elements can then be used to partition each sequence in parts, with the same total running time of .

Pseudocode

/**
 * d: Unsorted Array of Elements
 * n: Number of Elements
 * p: Number of Processors
 * return Sorted Array
 */
pMultiwayMergesort(d : Array, n : int, p : int) : Array {
	o := new array[0, n]                         // the output array
	
	for i = 1 to p in parallel do {              // each processor in parallel
	    s_i := d[(i-1) * n/p, i * n/p] 		     // Sequence of length n/p
	    sort(s_i)                                // sort locally
	
	    v_i := select_splitter(i * n/p)          // element with global rank i * n/p
	    (s_i,1 ,..., s_i,p) = sequence_partitioning(si, v_1, ..., v_p) // split s_i into subsequences
	    
	    o[(i-1) * n/p, i * n/p] := kWayMerge(s_1,i, ..., s_p,i)  // merge and assign to output array
	}
	return o
}

Analysis

Firstly, each processor sorts the assigned elements locally using a sorting algorithm with complexity . After that, the splitter elements have to be calculated in time . Finally, each group of splits have to be merged in parallel by each processor with a running time of using a sequential p-way merge algorithm. Thus, the overall running time is given by

.

Practical adaption and application

The multiway mergesort algorithm benifits from its scalability. The high parallelization capability makes it possible to sort very large amounts of data with many processors. In distributed systems, where memory is usually not a limiting resource and a large number of processors are available, its advantages are used.

However, other factors are important in such systems, which are not taken into account when modelling on a PRAM. For example, the communication overhead of exchanging data between processors could become a bottleneck when the data can no longer be accessed via the shared memory.

Sanders et al[3]. have presented a bulk synchronous parallel like algorithm for multilevel multiway mergesort, which divides processors into groups of size . All processors sort locally first. Unlike single level mergesort, these sequences are then partitioned into parts and assigned to the appropriate processor groups. These steps are repeated recursively in those groups. This reduces communication and especially avoids problems with many small messages. The hierarchial structure of the underlying real network can be used to define the processor groups (e.g. racks, clusters,...).

More Variants

Merge sort was one of the first sorting algorithms where optimal speed up was achieved, with Richard Cole using a clever subsampling algorithm to ensure O(1) merge. Other sophisticated parallel sorting algorithms can achieve the same or better time bounds with a lower constant. For example, in 1991 David Powers described a parallelized quicksort (and a related radix sort) that can operate in O(log n) time on a CRCW parallel random-access machine (PRAM) with n processors by performing partitioning implicitly. Powers further shows that a pipelined version of Batcher's Bitonic Mergesort at O((log n)2) time on a butterfly sorting network is in practice actually faster than his O(log n) sorts on a PRAM, and he provides detailed discussion of the hidden overheads in comparison, radix and parallel sorting.

References

  1. ^ Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2009) [1990]. Introduction to Algorithms (3rd ed.). MIT Press and McGraw-Hill. ISBN 0-262-03384-4.
  2. ^ Peter Sanders, Johannes Singler. 2008. Lecture Parallel algorithms Last visited 05.02.2020. http://algo2.iti.kit.edu/sanders/courses/paralg08/singler.pdf
  3. ^ a b Michael Axtmann, Timo Bingmann, Peter Sanders, and Christian Schulz. 2015. Practical Massively Parallel Sorting. In Proceedings of the 27th ACM symposium on Parallelism in Algorithms and Architectures (SPAA ’15). Association for Computing Machinery, New York, NY, USA, 13–23. DOI:https://doi.org/10.1145/2755573.2755595