User:ParAlgMergeSort/sandbox/Parallel merge sort

Parallel merge sort
Merge sort parallelizes well due to the use of the divide-and-conquer method. Several different parallel variants of the algorithm have been developed over the years. Some parallel merge sort algorithms are strongly related to the sequential top-down merge algorithm while others have a different general structure and use the K-way merge method.

Merge sort with parallel recursion
The sequential merge sort procedure can be described in two phases, the divide phase and the merge phase. The first consists of many recursive calls that repeatedly perform the same division process until the subsequences are trivially sorted (containing one or no element). An intuitive approach is the parallelization of those recursive calls. Following pseudocode describes the merge sort with parallel recursion using the fork and join keywords: // 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 $$\Theta(n)$$, which is only an improvement of $$\Theta(\log n)$$ 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.

Merge sort with parallel merging
Better parallelism can be achieved by using a parallel merge algorithm. Cormen et al. 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 in such a way 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: upper bound * off: offset */ algorithm parallelMergesort(A, lo, hi, B, off) is len := hi - lo + 1 if len == 1 then B[off] := A[lo] else let T[1..len] be a new array mid := ⌊(lo + hi) / 2⌋ mid' := mid - lo + 1 fork parallelMergesort(A, lo, mid, T, 1) parallelMergesort(A, mid + 1, hi, T, mid' + 1) join parallelMerge(T, 1, mid', mid' + 1, len, B, off) In order to analyze a Recurrence relation for the worst case span, the recursive calls of parallelMergesort have to be incorporated only once due to their parallel execution, obtaining

$T_{\infty}^{\text{sort} }(n) = T_{\infty}^{\text{sort}}\left(\frac {n} {2}\right) + T_{\infty}^{\text{merge}}(n) = T_{\infty}^{\text{sort}}\left(\frac {n} {2}\right) + \Theta \left( \log(n)^2\right)$.

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

The solution of this recurrence is given by

$T_{\infty}^{\text{sort}} = \Theta \left ( \log(n)^3 \right)$.

This parallel merge algorithm reaches a parallelism of $$\Theta \biggr({n \over (\log n)^2}\biggr)$$, which is much higher than the parallelism of the previous algorithm. Such a sort can perform well in practice when combined with a fast stable sequential sort, such as insertion sort, and a fast sequential merge as a base case for merging small arrays.

Parallel multiway merge sort
It seems arbitrary to restrict the merge sort algorithms to a binary merge method, since there are usually p > 2 processors available. A better approach may be to use a K-way merge method, a generalization of binary merge, in which k sorted sequences are merged together. This merge variant is well suited to describe a sorting algorithm on a PRAM.

Basic Idea
Given an unsorted sequence of $$n$$ elements, the goal is to sort the sequence with $$p$$ 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 $$S_1, ..., S_p$$ of length $\lceil \frac{n}{p} \rceil$. For simplification let n be a multiple of p, so that $\left\vert S_i \right\vert = \frac{n}{p}$ for $$i = 1, ..., p$$.

These sequences will be used to perform a multisequence selection/splitter selection. For $$i = 1,..., p$$, the algorithm determines splitter elements $$v_i$$ with global rank $k = i \frac{n}{p}$. Then the corresponding positions of $$v_1, ..., v_p$$ in each sequence $$S_i$$ are determined with binary search and thus the $$S_i$$ are further partitioned into $$p$$ subsequences $$S_{i,1}, ..., S_{i,p}$$ with $S_{i,j} := \{x \in S_i | rank(v_{j-1}) < rank(x) \le rank(v_j)\}$.

Furthermore, the elements of $$S_{1,i}, ..., S_{p,i}$$ are assigned to processor $$i$$, means all elements between rank $(i-1) \frac{n}{p}$ and rank $i \frac{n}{p}$, which are distributed over all $$S_i$$. Thus, each processor receives a sequence of sorted sequences. The fact that the rank $$k$$ of the splitter elements $$v_i$$ was chosen globally, provides two important properties: On the one hand, $$k$$ was chosen so that each processor can still operate on $n/p$ elements after assignment. The algorithm is perfectly load-balanced. On the other hand, all elements on processor $$i$$ are less than or equal to all elements on processor $$i+1$$. 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.

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

The presented sequential algorithm returns the indices of the splits in each sequence, e.g. the indices $$l_i$$ in sequences $$S_i$$ such that $$S_i[l_i]$$ has a global rank less than $$k$$ and $$\mathrm{rank}\left(S_i[l_i+1]\right) \ge k$$. algorithm msSelect(S : Array of sorted Sequences [S_1,..,S_p], k : int) is for i = 1 to p do (l_i, r_i) = (0, |S_i|-1) while there exists i: l_i < r_i do //pick Pivot Element in S_j[l_j],..,S_j[r_j], chose random j uniformly v := pickPivot(S, l, r) 	   for i = 1 to p do m_i = binarySearch(v, S_i[l_i, r_i]) //sequentially if m_1 + ... + m_p >= k then //m_1+ ... + m_p is the global rank of v 		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 $$p$$, the p-fold execution of the binarySearch method has a running time of $$\mathcal{O}\left(p\log\left(n/p\right)\right)$$. The expected recursion depth is $$\mathcal{O}\left(\log\left( \textstyle \sum_i |S_i| \right)\right) = \mathcal{O}(\log(n))$$ as in the ordinary Quickselect. Thus the overall expected running time is $$\mathcal{O}\left(p\log(n/p)\log(n)\right)$$.

Applied on the parallel multiway merge sort, this algorithm has to be invoked in parallel such that all splitter elements of rank $ i \frac n p$ for $$i = 1,.., p$$ are found simultaneously. These splitter elements can then be used to partition each sequence in $$p$$ parts, with the same total running time of $$\mathcal{O}\left(p\, \log(n/p)\log(n)\right)$$.

Pseudocode
Below, the complete pseudocode of the parallel multiway merge sort algorithm is given. We assume that there is a barrier synchronization before and after the multisequence selection such that every processor can determine the splitting elements and the sequence partiton properly. /** * d: Unsorted Array of Elements * n: Number of Elements * p: Number of Processors * return Sorted Array */ algorithm parallelMultiwayMergesort(d : Array, n : int, p : int) is o := new Array[0, n]                        // the output array for i = 1 to p do in parallel {             // each processor in parallel S_i := d[(i-1) * n/p, i * n/p] 	    // Sequence of length n/p sort(S_i)                               // sort locally synch v_i := msSelect([S_1,...,S_p], i * n/p)         // element with global rank i * n/p synch (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 $$n/p$$ elements locally using a sorting algorithm with complexity $$\mathcal{O}\left( n/p \; \log ( n/p) \right)$$. After that, the splitter elements have to be calculated in time $$\mathcal{O}\left(p \,\log(n/p) \log (n) \right)$$. Finally, each group of $$p$$ splits have to be merged in parallel by each processor with a running time of $$\mathcal{O}(\log(p)\; n/p )$$ using a sequential p-way merge algorithm. Thus, the overall running time is given by

$$\mathcal{O}\left( \frac n p \log\left(\frac n p\right) + p \log \left( \frac n p\right) \log (n) + \frac n p \log (p) \right)$$.

Practical adaption and application
The multiway merge sort algorithm is very scalable through its high parallelization capability, which allows the use of many processors. This makes the algorithm a viable candidate for sorting large amounts of data, such as those processed in computer clusters. Also, since in such systems memory is usually not a limiting resource, the disadvantage of space complexity of merge sort is negligible. However, other factors become important in such systems, which are not taken into account when modelling on a PRAM. Here, the following aspects need to be considered: Memory hierarchy, when the data does not fit into the processors cache, or the communication overhead of exchanging data between processors, which could become a bottleneck when the data can no longer be accessed via the shared memory.

Sanders et al. have presented in their paper a bulk synchronous parallel algorithm for multilevel multiway mergesort, which divides $$p$$ processors into $$r$$ groups of size $$p'$$. All processors sort locally first. Unlike single level multiway mergesort, these sequences are then partitioned into $$r$$ 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,...).

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