Highly Scalable Parallel Sorting

Total Page:16

File Type:pdf, Size:1020Kb

Highly Scalable Parallel Sorting so that they are in globally sorted order. A globally sorted order implies that every key on processor k is larger than every key on processor k − 1. Further, at Highly Scalable Parallel Sorting the end of execution, the number of keys stored on any processor should not be larger than some threshold n value p + tthresh (dictated by the memory availability Edgar Solomonik and Laxmikant V. Kale´ or desired final distribution). We will describe a new algorithm grounded on the Department of Computer Science basic principles of Histogram Sort [3] that can perform and scale well on modern supercomputer architectures. University of Illinois at Urbana-Champaign, Using our optimized implementation, we are able to Urbana, IL 61801, USA achieve an estimated 46.2% efficiency on 32,768 cores E-mail: [email protected], of BG/P (which corresponds to a speedup of roughly [email protected] 15,000). For a communication intensive algorithm such as sorting, this is a fairly impressive efficiency. Addi- tionally, the algorithm handles uniform as well as highly Abstract— Sorting is a commonly used process with non-uniform distributions of keys effectively. a wide breadth of applications in the high performance computing field. Early research in parallel processing Section 2 describes various parallel sorting algorithms has provided us with comprehensive analysis and theory as well as the original Histogram Sort. Section 3 docu- for parallel sorting algorithms. However, modern super- ments the optimizations we applied to the algorithm in computers have advanced rapidly in size and changed order to achieve better scaling. These include our probe significantly in architecture, forcing new adaptations to these algorithms. To fully utilize the potential of highly determination algorithm, all-to-all optimizations, and parallel machines, tens of thousands of processors are exploitations of overlap of communication with local used. Efficiently scaling parallel sorting on machines of sorting and merging. Section 4 introduces the specifics this magnitude is inhibited by the communication-intensive of our implementation, describes the machines we use problem of migrating large amounts of data between for testing, and analyzes the scaling and comparative processors. The challenge is to design a highly scalable sorting algorithm that uses minimal communication, max- speed of our parallel sorting algorithm. Section 5 will imizes overlap between computation and communication, suggest conclusions that can be drawn from our work and uses memory efficiently. This paper presents a scal- as well as potential areas for improvement. able extension of the Histogram Sorting method, making fundamental modifications to the original algorithm in II. PREVIOUS WORK order to minimize message contention and exploit overlap. We implement Histogram Sort, Sample Sort, and Radix Previous work has produced many alternative solu- Sort in CHARM++ and compare their performance. The choice of algorithm as well as the importance of the tions to address the problem of parallel sorting. The optimizations is validated by performance tests on two majority of parallel sorting algorithms can be classified predominant modern supercomputer architectures: XT4 as either merge-based or splitter-based. Merge-based at ORNL (Jaguar) and Blue Gene/P at ANL (Intrepid). parallel sorting algorithms rely on merging data be- tween pairs of processors. Such algorithms generally I. INTRODUCTION achieve a globally sorted order by constructing a sort- Algorithms for sorting are some of the most well- ing network between processors, which facilitates the studied and optimized algorithms in computer science. necessary sequence of merges. Splitter-based parallel Parallel sorting techniques, despite being well analyzed sorting algorithms aim to define a vector of splitters in a vast amount of literature, have not been sufficiently that subdivides the data into p approximately equal- tested or optimized on modern high performance super- sized sections. Each of the p − 1 splitters is simply a computers. Good scaling and performance of parallel key-value within the dataset. Thus for splitter si, where sorting is necessary for any parallel application that i 2 f0; 1; 2; :::; p − 2g, loc(si) 2 0; 1; 2; :::; n is the total depends on sorting. ChaNGa [1], an n-body Barnes-Hut number of keys smaller than si. Splitter si is valid if, n 1 n 1 tree-based gravity code [2], is an example of a highly (i + 1) p − 2 tthresh < loc(si) < (i + 1) p + 2 tthresh. parallel scientific code that uses sorting every iteration. Once these splitters are determined, each processor can The problem posed by parallel sorting is significantly send the appropriate portions of its data directly to the different and more challenging than the corresponding destination processors, which results in one round of sequential one. We begin with an unknown, unsorted dis- all-to-all communication. Notably, such splitter-based tribution of n keys over p processors. The algorithm has algorithms utilize minimal data movement, since the to sort and move the keys to the appropriate processor data associated with each key only moves once. Merge-based parallel sorting algorithms have been processor then produces p−1 splitters from the sp-sized extensively studied, though largely in the context of combined sample and broadcasts them to all other pro- sorting networks, which consider n=p ≈ 1. For n=p cessors. The splitters allow each processor to send each 1, these algorithms begin to suffer from heavy use of key to the correct final destination immediately. Some communication and difficulty of load balancing. There- implementations of Sample Sort also perform localized fore, splitter-based algorithms have been the primary load balancing between neighboring processors after the choice on most modern machines due to their minimal all-to-all. communication attribute and scalability. However, newer 1) Sorting by Regular Sampling: The Sorting by and much larger architectures have changed the prob- Regular Sampling technique is a reliable and practical lem statement further. Therefore, traditional approaches, variation of Sample Sort that uses a sample size of including splitter-based sorting algorithms, require re- s = p − 1 [9]. The algorithm is simple and executes evaluation and improvement. We will briefly detail some as follows. of these methods below. 1) Each processor sorts its local data. 2) Each processor selects a sample vector of size p−1 A. Bitonic Sort from its local data. The kth element of the sample n k+1 Bitonic Sort, a merge-based algorithm, was one of vector is element p × p of the local data. the earliest procedures for parallel sorting. It was intro- 3) The samples are sent to and merged on processor duced in 1968 by Batcher [4]. The basic idea behind 0, producing a combined sorted sample of size Bitonic Sort is to sort the data by merging bitonic p(p − 1). sequences.A bitonic sequence increases monotonically 4) Processor 0 defines and broadcasts a vector of p−1 1 then decreases monotonically. For n=p = 1, Θ(lg n) splitters with the kth splitter as element p(k + 2 ) merges are required, with each merge having a cost of of the combined sorted sample. Θ(lg n). The composed running time of Bitonic Sort for 5) Each processor sends its local data to the appro- n=p = 1 is Θ(lg2 n). Bitonic Sort can be generalized priate destination processors, as defined by the for n=p > 1, with a complexity of Θ(n lg2 n). Adaptive splitters, in one round of all-to-all communication. Bitonic Sorting, a modification of Bitonic Sort, avoids 6) Each processor merges the data chunks it receives. unnecessary comparisons, which results in an improved, It has been shown that if n is sufficiently large, no 2n optimal complexity of Θ(n lg n) [5]. processor will end up with more than p keys [9]. In Unfortunately, each step of Bitonic Sort requires practice, the algorithm often achieves almost perfect movement of data between pairs of processors. Like load balance. most merge-based algorithms, Bitonic Sort can perform Though attractive for its simplicity, this approach is very well when n=p (where n is the total number of problematic for scaling beyond a few thousand proces- keys and p is the number of processors) is small, since sors on modern machines. The algorithm requires that it operates in-place and effectively combines messages. a combined sample p(p − 1) keys be merged on one On the other hand, its performance quickly degrades as processor, which becomes an unachievable task since it n=p becomes large, which is the much more realistic demands Θ(p2) memory and work on a single proces- scenario for typical scientific applications. The major sor. For example, on 16,384 processors, the combined drawback of Bitonic Sort on modern architectures is sample of 64-bit keys would require 16 GB of memory. that it moves the data Θ(lg p) times, which turns into Despite this limitation, due to the popularity of Sorting costly bottleneck if we scale to higher problem sizes by Regular Sampling, we provide performance results or a larger number of processors. Since this algorithm of our implementation of the algorithm (see Figure 7). is old and very well-studied, we will not go into any For a more thorough description and theoretical analysis deep analysis or testing of it. Nevertheless, Bitonic of Sample Sort, refer to Li et al. [10]. Sort has laid groundwork for much of parallel sorting 2) Sorting by Random Sampling: Sorting by Ran- research and continues to influence modern algorithms. dom Sampling is an interesting alternative to Regular One good comparative study of this algorithm has been Sampling [8], [11], [6]. The main difference between documented by Blelloch et al. [6]. the two sampling techniques is that a random sample is flexible in size and collected randomly from each B.
Recommended publications
  • 2.3 Quicksort
    2.3 Quicksort ‣ quicksort ‣ selection ‣ duplicate keys ‣ system sorts Algorithms, 4th Edition · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · January 30, 2011 12:46:16 PM Two classic sorting algorithms Critical components in the world’s computational infrastructure. • Full scientific understanding of their properties has enabled us to develop them into practical system sorts. • Quicksort honored as one of top 10 algorithms of 20th century in science and engineering. Mergesort. last lecture • Java sort for objects. • Perl, C++ stable sort, Python stable sort, Firefox JavaScript, ... Quicksort. this lecture • Java sort for primitive types. • C qsort, Unix, Visual C++, Python, Matlab, Chrome JavaScript, ... 2 ‣ quicksort ‣ selection ‣ duplicate keys ‣ system sorts 3 Quicksort Basic plan. • Shuffle the array. • Partition so that, for some j - element a[j] is in place - no larger element to the left of j j - no smaller element to the right of Sir Charles Antony Richard Hoare • Sort each piece recursively. 1980 Turing Award input Q U I C K S O R T E X A M P L E shu!e K R A T E L E P U I M Q C X O S partitioning element partition E C A I E K L P U T M Q R X O S not greater not less sort left A C E E I K L P U T M Q R X O S sort right A C E E I K L M O P Q R S T U X result A C E E I K L M O P Q R S T U X Quicksort overview 4 Quicksort partitioning Basic plan.
    [Show full text]
  • Advanced Topics in Sorting
    Advanced Topics in Sorting complexity system sorts duplicate keys comparators 1 complexity system sorts duplicate keys comparators 2 Complexity of sorting Computational complexity. Framework to study efficiency of algorithms for solving a particular problem X. Machine model. Focus on fundamental operations. Upper bound. Cost guarantee provided by some algorithm for X. Lower bound. Proven limit on cost guarantee of any algorithm for X. Optimal algorithm. Algorithm with best cost guarantee for X. lower bound ~ upper bound Example: sorting. • Machine model = # comparisons access information only through compares • Upper bound = N lg N from mergesort. • Lower bound ? 3 Decision Tree a < b yes no code between comparisons (e.g., sequence of exchanges) b < c a < c yes no yes no a b c b a c a < c b < c yes no yes no a c b c a b b c a c b a 4 Comparison-based lower bound for sorting Theorem. Any comparison based sorting algorithm must use more than N lg N - 1.44 N comparisons in the worst-case. Pf. Assume input consists of N distinct values a through a . • 1 N • Worst case dictated by tree height h. N ! different orderings. • • (At least) one leaf corresponds to each ordering. Binary tree with N ! leaves cannot have height less than lg (N!) • h lg N! lg (N / e) N Stirling's formula = N lg N - N lg e N lg N - 1.44 N 5 Complexity of sorting Upper bound. Cost guarantee provided by some algorithm for X. Lower bound. Proven limit on cost guarantee of any algorithm for X.
    [Show full text]
  • Sorting Algorithm 1 Sorting Algorithm
    Sorting algorithm 1 Sorting algorithm In computer science, a sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (such as search and merge algorithms) that require sorted lists to work correctly; it is also often useful for canonicalizing data and for producing human-readable output. More formally, the output must satisfy two conditions: 1. The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order); 2. The output is a permutation, or reordering, of the input. Since the dawn of computing, the sorting problem has attracted a great deal of research, perhaps due to the complexity of solving it efficiently despite its simple, familiar statement. For example, bubble sort was analyzed as early as 1956.[1] Although many consider it a solved problem, useful new sorting algorithms are still being invented (for example, library sort was first published in 2004). Sorting algorithms are prevalent in introductory computer science classes, where the abundance of algorithms for the problem provides a gentle introduction to a variety of core algorithm concepts, such as big O notation, divide and conquer algorithms, data structures, randomized algorithms, best, worst and average case analysis, time-space tradeoffs, and lower bounds. Classification Sorting algorithms used in computer science are often classified by: • Computational complexity (worst, average and best behaviour) of element comparisons in terms of the size of the list . For typical sorting algorithms good behavior is and bad behavior is .
    [Show full text]
  • Visvesvaraya Technological University a Project Report
    ` VISVESVARAYA TECHNOLOGICAL UNIVERSITY “Jnana Sangama”, Belagavi – 590 018 A PROJECT REPORT ON “PREDICTIVE SCHEDULING OF SORTING ALGORITHMS” Submitted in partial fulfillment for the award of the degree of BACHELOR OF ENGINEERING IN COMPUTER SCIENCE AND ENGINEERING BY RANJIT KUMAR SHA (1NH13CS092) SANDIP SHAH (1NH13CS101) SAURABH RAI (1NH13CS104) GAURAV KUMAR (1NH13CS718) Under the guidance of Ms. Sridevi (Senior Assistant Professor, Dept. of CSE, NHCE) DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING NEW HORIZON COLLEGE OF ENGINEERING (ISO-9001:2000 certified, Accredited by NAAC ‘A’, Permanently affiliated to VTU) Outer Ring Road, Panathur Post, Near Marathalli, Bangalore – 560103 ` NEW HORIZON COLLEGE OF ENGINEERING (ISO-9001:2000 certified, Accredited by NAAC ‘A’ Permanently affiliated to VTU) Outer Ring Road, Panathur Post, Near Marathalli, Bangalore-560 103 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING CERTIFICATE Certified that the project work entitled “PREDICTIVE SCHEDULING OF SORTING ALGORITHMS” carried out by RANJIT KUMAR SHA (1NH13CS092), SANDIP SHAH (1NH13CS101), SAURABH RAI (1NH13CS104) and GAURAV KUMAR (1NH13CS718) bonafide students of NEW HORIZON COLLEGE OF ENGINEERING in partial fulfillment for the award of Bachelor of Engineering in Computer Science and Engineering of the Visvesvaraya Technological University, Belagavi during the year 2016-2017. It is certified that all corrections/suggestions indicated for Internal Assessment have been incorporated in the report deposited in the department library. The project report has been approved as it satisfies the academic requirements in respect of Project work prescribed for the Degree. Name & Signature of Guide Name Signature of HOD Signature of Principal (Ms. Sridevi) (Dr. Prashanth C.S.R.) (Dr. Manjunatha) External Viva Name of Examiner Signature with date 1.
    [Show full text]
  • Super Scalar Sample Sort
    Super Scalar Sample Sort Peter Sanders1 and Sebastian Winkel2 1 Max Planck Institut f¨ur Informatik Saarbr¨ucken, Germany, [email protected] 2 Chair for Prog. Lang. and Compiler Construction Saarland University, Saarbr¨ucken, Germany, [email protected] Abstract. Sample sort, a generalization of quicksort that partitions the input into many pieces, is known as the best practical comparison based sorting algorithm for distributed memory parallel computers. We show that sample sort is also useful on a single processor. The main algorith- mic insight is that element comparisons can be decoupled from expensive conditional branching using predicated instructions. This transformation facilitates optimizations like loop unrolling and software pipelining. The final implementation, albeit cache efficient, is limited by a linear num- ber of memory accesses rather than the O(n log n) comparisons. On an Itanium 2 machine, we obtain a speedup of up to 2 over std::sort from the GCC STL library, which is known as one of the fastest available quicksort implementations. 1 Introduction Counting comparisons is the most common way to compare the complexity of comparison based sorting algorithms. Indeed, algorithms like quicksort with good sampling strategies [9,14] or merge sort perform close to the lower bound of log n! n log n comparisons3 for sorting n elements and are among the best algorithms≈ in practice (e.g., [24, 20, 5]). At least for numerical keys it is a bit astonishing that comparison operations alone should be good predictors for ex- ecution time because comparing numbers is equivalent to subtraction — an operation of negligible cost compared to memory accesses.
    [Show full text]
  • How to Sort out Your Life in O(N) Time
    How to sort out your life in O(n) time arel Číže @kaja47K funkcionaklne.cz I said, "Kiss me, you're beautiful - These are truly the last days" Godspeed You! Black Emperor, The Dead Flag Blues Everyone, deep in their hearts, is waiting for the end of the world to come. Haruki Murakami, 1Q84 ... Free lunch 1965 – 2022 Cramming More Components onto Integrated Circuits http://www.cs.utexas.edu/~fussell/courses/cs352h/papers/moore.pdf He pays his staff in junk. William S. Burroughs, Naked Lunch Sorting? quicksort and chill HS 1964 QS 1959 MS 1945 RS 1887 quicksort, mergesort, heapsort, radix sort, multi- way merge sort, samplesort, insertion sort, selection sort, library sort, counting sort, bucketsort, bitonic merge sort, Batcher odd-even sort, odd–even transposition sort, radix quick sort, radix merge sort*, burst sort binary search tree, B-tree, R-tree, VP tree, trie, log-structured merge tree, skip list, YOLO tree* vs. hashing Robin Hood hashing https://cs.uwaterloo.ca/research/tr/1986/CS-86-14.pdf xs.sorted.take(k) (take (sort xs) k) qsort(lotOfIntegers) It may be the wrong decision, but fuck it, it's mine. (Mark Z. Danielewski, House of Leaves) I tell you, my man, this is the American Dream in action! We’d be fools not to ride this strange torpedo all the way out to the end. (HST, FALILV) Linear time sorting? I owe the discovery of Uqbar to the conjunction of a mirror and an Encyclopedia. (Jorge Luis Borges, Tlön, Uqbar, Orbis Tertius) Sorting out graph processing https://github.com/frankmcsherry/blog/blob/master/posts/2015-08-15.md Radix Sort Revisited http://www.codercorner.com/RadixSortRevisited.htm Sketchy radix sort https://github.com/kaja47/sketches (thinking|drinking|WTF)* I know they accuse me of arrogance, and perhaps misanthropy, and perhaps of madness.
    [Show full text]
  • Advanced Topics in Sorting  List RSS News Items in Reverse Chronological Order
    Sorting applications Sorting algorithms are essential in a broad variety of applications Organize an MP3 library. Display Google PageRank results. Advanced Topics in Sorting List RSS news items in reverse chronological order. Find the median. Find the closest pair. Binary search in a database. [email protected] Identify statistical outliers. Find duplicates in a mailing list. [email protected] Data compression. Computer graphics. Computational biology. Supply chain management. Load balancing on a parallel computer. http://www.4shared.com/file/79096214/fb2ed224/lect01.html . Sorting algorithms Which algorithm to use? Many sorting algorithms to choose from Applications have diverse attributes Stable? Internal sorts Multiple keys? Insertion sort, selection sort, bubblesort, shaker sort. Quicksort, mergesort, heapsort, samplesort, shellsort. Deterministic? Solitaire sort, red-black sort, splaysort, Dobosiewicz sort, psort, ... Keys all distinct? External sorts Multiple key types? Poly-phase mergesort, cascade-merge, oscillating sort. Linked list or arrays? Radix sorts Large or small records? Distribution, MSD, LSD. 3-way radix quicksort. Is your file randomly ordered? Parallel sorts Need guaranteed performance? Bitonic sort, Batcher even-odd sort. Smooth sort, cube sort, column sort. Cannot cover all combinations of attributes. GPUsort. 1 Case study 1 Case study 2 Problem Problem Sort a huge randomly-ordered file of small Sort a huge file that is already almost in records. order. Example Example Process transaction records for a phone Re-sort a huge database after a few company. changes. Which sorting method to use? Which sorting method to use? 1. Quicksort: YES, it's designed for this problem 1. Quicksort: probably no, insertion simpler and faster 2.
    [Show full text]
  • Sorting Algorithm 1 Sorting Algorithm
    Sorting algorithm 1 Sorting algorithm A sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order. Efficient sorting is important for optimizing the use of other algorithms (such as search and merge algorithms) which require input data to be in sorted lists; it is also often useful for canonicalizing data and for producing human-readable output. More formally, the output must satisfy two conditions: 1. The output is in nondecreasing order (each element is no smaller than the previous element according to the desired total order); 2. The output is a permutation (reordering) of the input. Since the dawn of computing, the sorting problem has attracted a great deal of research, perhaps due to the complexity of solving it efficiently despite its simple, familiar statement. For example, bubble sort was analyzed as early as 1956.[1] Although many consider it a solved problem, useful new sorting algorithms are still being invented (for example, library sort was first published in 2006). Sorting algorithms are prevalent in introductory computer science classes, where the abundance of algorithms for the problem provides a gentle introduction to a variety of core algorithm concepts, such as big O notation, divide and conquer algorithms, data structures, randomized algorithms, best, worst and average case analysis, time-space tradeoffs, and upper and lower bounds. Classification Sorting algorithms are often classified by: • Computational complexity (worst, average and best behavior) of element comparisons in terms of the size of the list (n). For typical serial sorting algorithms good behavior is O(n log n), with parallel sort in O(log2 n), and bad behavior is O(n2).
    [Show full text]
  • Mergesort and Quicksort
    Algorithms ROBERT SEDGEWICK | KEVIN WAYNE 2.2 MERGESORT ‣ mergesort ‣ bottom-up mergesort Algorithms ‣ sorting complexity FOURTH EDITION ‣ comparators ‣ stability ROBERT SEDGEWICK | KEVIN WAYNE http://algs4.cs.princeton.edu Two classic sorting algorithms: mergesort and quicksort Critical components in the world’s computational infrastructure. ・Full scientific understanding of their properties has enabled us to develop them into practical system sorts. ・Quicksort honored as one of top 10 algorithms of 20th century in science and engineering. Mergesort. [this lecture] ... Quicksort. [next lecture] ... 2 2.2 MERGESORT ‣ mergesort ‣ bottom-up mergesort Algorithms ‣ sorting complexity ‣ comparators ‣ stability ROBERT SEDGEWICK | KEVIN WAYNE http://algs4.cs.princeton.edu Mergesort Basic plan. ・Divide array into two halves. ・Recursively sort each half. ・Merge two halves. input M E R G E S O R T E X A M P L E sort left half E E G M O R R S T E X A M P L E sort right half E E G M O R R S A E E L M P T X merge results A E E E E G L M M O P R R S T X Mergesort overview 4 Abstract in-place merge demo Goal. Given two sorted subarrays a[lo] to a[mid] and a[mid+1] to a[hi], replace with sorted subarray a[lo] to a[hi]. lo mid mid+1 hi a[] E E G M R A C E R T sorted sorted 5 Abstract in-place merge demo Goal. Given two sorted subarrays a[lo] to a[mid] and a[mid+1] to a[hi], replace with sorted subarray a[lo] to a[hi].
    [Show full text]
  • Algorithms ROBERT SEDGEWICK | KEVIN WAYNE
    Algorithms ROBERT SEDGEWICK | KEVIN WAYNE 2.2 MERGESORT ‣ mergesort ‣ bottom-up mergesort Algorithms ‣ sorting complexity FOURTH EDITION ‣ divide-and-conquer ROBERT SEDGEWICK | KEVIN WAYNE https://algs4.cs.princeton.edu Last updated on 9/26/19 4:36 AM Two classic sorting algorithms: mergesort and quicksort Critical components in the world’s computational infrastructure. Full scientific understanding of their properties has enabled us to develop them into practical system sorts. Quicksort honored as one of top 10 algorithms of 20th century in science and engineering. Mergesort. [this lecture] ... Quicksort. [next lecture] ... 2 2.2 MERGESORT ‣ mergesort ‣ bottom-up mergesort Algorithms ‣ sorting complexity ‣ divide-and-conquer ROBERT SEDGEWICK | KEVIN WAYNE https://algs4.cs.princeton.edu Mergesort Basic plan. Divide array into two halves. Recursively sort each half. Merge two halves. input M E R G E S O R T E X A M P L E sort left half E E G M O R R S T E X A M P L E sort right half E E G M O R R S A E E L M P T X merge results A E E E E G L M M O P R R S T X Mergesort overview 4 Abstract in-place merge demo Goal. Given two sorted subarrays a[lo] to a[mid] and a[mid+1] to a[hi], replace with sorted subarray a[lo] to a[hi]. lo mid mid+1 hi a[] E E G M R A C E R T sorted sorted 5 Mergesort: Transylvanian–Saxon folk dance http://www.youtube.com/watch?v=XaqR3G_NVoo 6 Merging: Java implementation private static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) { for (int k = lo; k <= hi; k++) copy aux[k] = a[k]; int i = lo, j = mid+1; merge for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; else if (j > hi) a[k] = aux[i++]; else if (less(aux[j], aux[i])) a[k] = aux[j++]; else a[k] = aux[i++]; } } lo i mid j hi aux[] A G L O R H I M S T k a[] A G H I L M 7 Mergesort quiz 1 How many calls does merge() make to less() in order to merge two sorted subarrays, each of length n / 2, into a sorted array of length n? A.
    [Show full text]
  • Comparison Sorts Name Best Average Worst Memory Stable Method Other Notes Quicksort Is Usually Done in Place with O(Log N) Stack Space
    Comparison sorts Name Best Average Worst Memory Stable Method Other notes Quicksort is usually done in place with O(log n) stack space. Most implementations on typical in- are unstable, as stable average, worst place sort in-place partitioning is case is ; is not more complex. Naïve Quicksort Sedgewick stable; Partitioning variants use an O(n) variation is stable space array to store the worst versions partition. Quicksort case exist variant using three-way (fat) partitioning takes O(n) comparisons when sorting an array of equal keys. Highly parallelizable (up to O(log n) using the Three Hungarian's Algorithmor, more Merge sort worst case Yes Merging practically, Cole's parallel merge sort) for processing large amounts of data. Can be implemented as In-place merge sort — — Yes Merging a stable sort based on stable in-place merging. Heapsort No Selection O(n + d) where d is the Insertion sort Yes Insertion number of inversions. Introsort No Partitioning Used in several STL Comparison sorts Name Best Average Worst Memory Stable Method Other notes & Selection implementations. Stable with O(n) extra Selection sort No Selection space, for example using lists. Makes n comparisons Insertion & Timsort Yes when the data is already Merging sorted or reverse sorted. Makes n comparisons Cubesort Yes Insertion when the data is already sorted or reverse sorted. Small code size, no use Depends on gap of call stack, reasonably sequence; fast, useful where Shell sort or best known is No Insertion memory is at a premium such as embedded and older mainframe applications. Bubble sort Yes Exchanging Tiny code size.
    [Show full text]
  • Data Sorting Using Graphics Processing Units
    Telfor Journal, Vol. 4, No. 1, 2012. 43 Data Sorting Using Graphics Processing Units Marko J. Mišić and Milo V. Tomašević 1 produce human-readable form of data, etc. Sorting Abstract — Graphics processing units (GPUs) have been operation is not only a part of many parallel applications, increasingly used for general-purpose computation in recent but also an important benchmark for parallel systems. It years. The GPU accelerated applications are found in both consumes a significant bandwidth for communication scientific and commercial domains. Sorting is considered as among processors since highly rated sorting algorithms one of the very important operations in many applications, so its efficient implementation is essential for the overall access data in irregular patterns [1]. This is very important application performance. This paper represents an effort to for the GPUs, since they need many calculations per one analyze and evaluate the implementations of the memory access to achieve their peak performance. Sorting representative sorting algorithms on the graphics processing algorithms usually do not have high computation to global units. Three sorting algorithms (Quicksort, Merge sort, and memory access ratio, which puts the emphasis on Radix sort) were evaluated on the Compute Unified Device algorithms that access the memory in favorable ways. Architecture (CUDA) platform that is used to execute applications on NVIDIA graphics processing units. The goal of this paper is to present a short survey and Algorithms were tested and evaluated using an automated performance analysis of sorting algorithms on graphics test environment with input datasets of different processing units. It presents three representative sorting characteristics.
    [Show full text]