Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Merge sort
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Parallel merge sort== Merge sort parallelizes well due to the use of the [[Divide-and-conquer algorithm|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 algorithm|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.<ref name="clrs">{{Harvtxt|Cormen|Leiserson|Rivest|Stein|2009|pp=797β805}}</ref> Following pseudocode describes the merge sort with parallel recursion using the [[Forkβjoin model|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 [[Analysis of parallel algorithms#Overview|span]] of <math>\Theta(n)</math>, which is only an improvement of <math>\Theta(\log n)</math> 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 === {{Main|Merge algorithm#Parallel merge}} Better parallelism can be achieved by using a parallel [[merge algorithm]]. [[Introduction to Algorithms|Cormen et al.]] present a binary variant that merges two sorted sub-sequences into one sorted output sequence.<ref name="clrs" /> 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''' <nowiki> B[off] := A[lo]</nowiki> '''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 <math display="block"> 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).</math> For detailed information about the complexity of the parallel merge procedure, see [[Merge algorithm#Parallel merge|Merge algorithm]]. The solution of this recurrence is given by <math display="block"> T_{\infty}^{\text{sort}} = \Theta \left ( \log(n)^3 \right).</math> This parallel merge algorithm reaches a parallelism of <math display="inline">\Theta \left(\frac{n}{(\log n)^2}\right)</math>, 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.<ref>Victor J. Duvanenko "Parallel Merge Sort" Dr. Dobb's Journal & blog [https://duvanenko.tech.blog/2018/01/13/parallel-merge-sort/] and GitHub repo C++ implementation [https://github.com/DragonSpit/ParallelAlgorithms]</ref> === 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 algorithm|K-way merge]] method, a generalization of binary merge, in which <math>k</math> sorted sequences are merged. This merge variant is well suited to describe a sorting algorithm on a [[Parallel random-access machine|PRAM]].<ref>{{cite web|author1=Peter Sanders |author2=Johannes Singler |date=2008 |title=Lecture ''Parallel algorithms'' |url=http://algo2.iti.kit.edu/sanders/courses/paralg08/singler.pdf |access-date=2020-05-02}}</ref><ref name=":0">{{Cite book|year=2015|doi=10.1145/2755573.2755595|last1=Axtmann|first1=Michael|last2=Bingmann|first2=Timo|last3=Sanders|first3=Peter|last4=Schulz|first4=Christian|title=Proceedings of the 27th ACM symposium on Parallelism in Algorithms and Architectures |chapter=Practical Massively Parallel Sorting |pages=13β23|isbn=9781450335881|s2cid=18249978|chapter-url=https://publikationen.bibliothek.kit.edu/1000050651/37296033}}</ref> ==== Basic idea ==== [[File:Parallel_multiway_mergesort_process.svg|alt=|thumb|The parallel multiway mergesort process on four processors <math>t_0</math> to <math>t_3</math>.]] Given an unsorted sequence of <math>n</math> elements, the goal is to sort the sequence with <math>p</math> available [[Processor (computing)|processors]]. These elements are distributed equally among all processors and sorted locally using a sequential [[Sorting algorithm]]. Hence, the sequence consists of sorted sequences <math>S_1, ..., S_p</math> of length <math display="inline">\lceil \frac{n}{p} \rceil</math>. For simplification let <math>n</math> be a multiple of <math>p</math>, so that <math display="inline">\left\vert S_i \right\vert = \frac{n}{p}</math> for <math>i = 1, ..., p</math>. These sequences will be used to perform a multisequence selection/splitter selection. For <math>j = 1,..., p</math>, the algorithm determines splitter elements <math>v_j </math> with global rank <math display="inline">k = j \frac{n}{p}</math>. Then the corresponding positions of <math>v_1, ..., v_p</math> in each sequence <math>S_i</math> are determined with [[Binary search algorithm|binary search]] and thus the <math>S_i</math> are further partitioned into <math>p</math> subsequences <math>S_{i,1}, ..., S_{i,p}</math> with <math display="inline">S_{i,j} := \{x \in S_i | rank(v_{j-1}) < rank(x) \le rank(v_j)\}</math>. Furthermore, the elements of <math>S_{1,i}, ..., S_{p,i}</math> are assigned to processor <math>i</math>, means all elements between rank <math display="inline">(i-1) \frac{n}{p}</math> and rank <math display="inline">i \frac{n}{p}</math>, which are distributed over all <math>S_i</math>. Thus, each processor receives a sequence of sorted sequences. The fact that the rank <math>k</math> of the splitter elements <math>v_i</math> was chosen globally, provides two important properties: On the one hand, <math>k</math> was chosen so that each processor can still operate on <math display="inline">n/p</math> elements after assignment. The algorithm is perfectly [[Load balancing (computing)|load-balanced]]. On the other hand, all elements on processor <math>i</math> are less than or equal to all elements on processor <math>i+1</math>. Hence, each processor performs the [[K-way merge algorithm|''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. ==== Multi-sequence selection ==== In its simplest form, given <math>p</math> sorted sequences <math>S_1, ..., S_p</math> distributed evenly on <math>p</math> processors and a rank <math>k</math>, the task is to find an element <math>x</math> with a global rank <math>k</math> in the union of the sequences. Hence, this can be used to divide each <math>S_i</math> in two parts at a splitter index <math>l_i</math>, where the lower part contains only elements which are smaller than <math>x</math>, while the elements bigger than <math>x</math> are located in the upper part. The presented sequential algorithm returns the indices of the splits in each sequence, e.g. the indices <math>l_i</math> in sequences <math>S_i</math> such that <math>S_i[l_i]</math> has a global rank less than <math>k</math> and <math>\mathrm{rank}\left(S_i[l_i+1]\right) \ge k</math>.<ref>{{cite web |author=Peter Sanders |date=2019 |title=Lecture ''Parallel algorithms'' |url=http://algo2.iti.kit.edu/sanders/courses/paralg19/vorlesung.pdf |access-date=2020-05-02}}</ref> '''algorithm'''<nowiki> msSelect(S : Array of sorted Sequences [S_1,..,S_p], k : int) </nowiki>'''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 [[Parallel random-access machine|PRAM]] model is chosen. If the data is evenly distributed over all <math>p</math>, the p-fold execution of the ''binarySearch'' method has a running time of <math>\mathcal{O}\left(p\log\left(n/p\right)\right)</math>. The expected recursion depth is <math>\mathcal{O}\left(\log\left( \textstyle \sum_i |S_i| \right)\right) = \mathcal{O}(\log(n))</math> as in the ordinary [[Quickselect]]. Thus the overall expected running time is <math>\mathcal{O}\left(p\log(n/p)\log(n)\right)</math>. Applied on the parallel multiway merge sort, this algorithm has to be invoked in parallel such that all splitter elements of rank <math display="inline"> i \frac n p</math> for <math>i = 1,.., p</math> are found simultaneously. These splitter elements can then be used to partition each sequence in <math>p</math> parts, with the same total running time of <math>\mathcal{O}\left(p\, \log(n/p)\log(n)\right)</math>. ==== 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 partition 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 <nowiki> S_i := d[(i-1) * n/p, i * n/p] // Sequence of length n/p</nowiki> 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 <math>n/p</math> elements locally using a sorting algorithm with complexity <math>\mathcal{O}\left( n/p \; \log ( n/p) \right)</math>. After that, the splitter elements have to be calculated in time <math>\mathcal{O}\left(p \,\log(n/p) \log (n) \right)</math>. Finally, each group of <math>p</math> splits have to be merged in parallel by each processor with a running time of <math>\mathcal{O}(\log(p)\; n/p )</math> using a sequential [[Merge algorithm|p-way merge algorithm]]. Thus, the overall running time is given by <math>\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)</math>. ==== 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 cluster]]s. 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 [[Parallel random-access machine|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. [[Peter Sanders (computer scientist)|Sanders]] et al. have presented in their paper a [[bulk synchronous parallel]] algorithm for multilevel multiway mergesort, which divides <math>p</math> processors into <math>r</math> groups of size <math>p'</math>. All processors sort locally first. Unlike single level multiway mergesort, these sequences are then partitioned into <math>r</math> 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 hierarchical structure of the underlying real network can be used to define the processor groups (e.g. [[19-inch rack|racks]], [[Computer cluster|clusters]],...).<ref name=":0" /> === 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.<ref>{{Cite journal |last1=Cole |first1=Richard |date=August 1988 |title=Parallel merge sort |journal=SIAM J. Comput. |volume=17 |issue=4 |pages=770β785 |citeseerx=10.1.1.464.7118 |doi=10.1137/0217049|s2cid=2416667 }}</ref> 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.<ref>{{cite book |last=Powers |first=David M. W. |chapter-url=http://citeseer.ist.psu.edu/327487.html |chapter=Parallelized Quicksort and Radixsort with Optimal Speedup |title=Proceedings of International Conference on Parallel Computing Technologies, Novosibirsk |date=1991 |archive-url=https://web.archive.org/web/20070525234405/http://citeseer.ist.psu.edu/327487.html |archive-date=2007-05-25}}</ref> Powers further shows that a pipelined version of Batcher's [[Bitonic sorter|Bitonic Mergesort]] at ''O''((log ''n'')<sup>2</sup>) 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.<ref>{{cite conference |last=Powers |first=David M. W. |url= http://david.wardpowers.info/Research/AI/papers/199501-ACAW-PUPC.pdf |title=Parallel Unification: Practical Complexity |conference=Australasian Computer Architecture Workshop Flinders University |date=January 1995}}</ref>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)