Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Algorithms
  • Analysis of Algorithms
  • Sorting
  • Searching
  • Greedy
  • Recursion
  • Backtracking
  • Dynamic Programming
  • Divide and Conquer
  • Geometric Algorithms
  • Mathematical Algorithms
  • Pattern Searching
  • Bitwise Algorithms
  • Branch & Bound
  • Randomized Algorithms
Open In App
Next Article:
Parallel vs Sequential Stream in Java
Next article icon

Serial Sort v/s Parallel Sort in Java

Last Updated : 13 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

We often need to sort array while programming. For this, we use inbuilt method provided by Java in Arrays class i.e sort(). sort() method uses merge sort or Time Sort to sort the array elements. In both the cases sort() method sequentially sort the elements of an array. 
In Java 8, there is a new API introduced for sorting which is Parallel Sorting. Parallel Sort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool. Fork/Join implements a work stealing algorithm where in a idle thread can steal tasks queued up in another thread. 
For Example, the following code is a program that sorts a randomized array of doubles using Arrays.sort() and Arrays.parallelSort(). This program simply measures the performance difference between this two approaches. : 

java




// Java program to demonstrate time taken by sort()
// and parallelSort() methods.
import java.util.Arrays;
  
public class ParallelSortTest
{
    private static final int BASE_ARRAY_SIZE = 10000;
  
    // A utility function to generate and return 
    // an array of given size filled with randomly
    // generated elements.
    public static double[] generateArray(int size)
    {
        if (size <= 0 || size > Integer.MAX_VALUE)
            return null;
  
        double[] result = new double[size];
        for (int i = 0; i < size; i++)
            result[i] = Math.random();
  
        return result;
    }
  
    // Driver code to compare two sortings
    public static void main(String[] args)
    {
        for (int i = 1; i < 10000; i *= 10)
        {
            int size = BASE_ARRAY_SIZE * i;
            double[] arr1 = generateArray(size);
  
            // Creating a copy of arr1 so that we can
            // use same content for both sortings.
            double[] arr2 = Arrays.copyOf(arr1, arr1.length);
            System.out.println("Array Size: " + size);
  
            // Sorting arr1[] using serial sort
            long startTime = System.currentTimeMillis();
            Arrays.sort(arr1);
            long endTime = System.currentTimeMillis();
            System.out.println("Time take in serial: " +
                            (endTime - startTime) + "ms.");
  
            // Sorting arr2[] using serial sort
            startTime = System.currentTimeMillis();
            Arrays.parallelSort(arr2);
            endTime = System.currentTimeMillis();
            System.out.println("Time take in parallel: "
                            + (endTime - startTime) + "ms.");
            System.out.println();
        }
    }
}
 
 

Environment :

2.6 GHz Intel Core i7  java version "1.8.0_25"

Time Complexity: O(N log(N)) 
Auxiliary Space: O(N)

Note : Required Time may vary due to random values in the array. The key differences between both the algorithm are as follow : 1) Arrays.sort() : is a sequential sorting.

  • The API uses single thread for the operation.
  • It takes bit longer time to perform the operation.

2. Arrays.ParallelSort() : is a parallel sorting.

  • The API uses multiple threads for the operation.
  • It’s faster when there are a lot of elements whereas slower for lesser elements.

Analysis : The results show that parallel sorting on a multicore machine can achieve performance improvements at 1 million or more elements. While below this threshold it may actually be slower than sequential sorting. This result meets the expectation, and the suitable size here may be 1 million. Your mileage may vary, it depends on your environment. Explanation : Now, let’s take a look at the code to figure out how this parallel sorting works.

    public static void parallelSort(double[] a) {          int n = a.length, p, g;          if (n <= MIN_ARRAY_SORT_GRAN ||              (p = ForkJoinPool.getCommonPoolParallelism()) == 1)              DualPivotQuicksort.sort(a, 0, n - 1, null, 0, 0);          else              new ArraysParallelSortHelpers.FJDouble.Sorter                  (null, a, new double[n], 0, n, 0,                   ((g = n / (p << 2)) <= MIN_ARRAY_SORT_GRAN) ?                   MIN_ARRAY_SORT_GRAN : g).invoke();      }

As we can see, there is a minimum granularity (java.util.Arrays.MIN_ARRAY_SORT_GRAN = 8192 [0x2000]), and if the length of the array is less than the minimum granularity, it is sorted using the DualPivotQuicksort.sort directly instead of the sorting task partition. Typically, using smaller sizes results in memory contention across tasks that makes parallel speedups unlikely. 
Another notable judgement is ForkJoinPool.getCommonPoolParallelism() which returns the targeted parallelism level of the common pool (by default, equal to the number of available processors Runtime.getRuntime().availableProcessors()). And if your machine has only 1 worker thread, it will not use parallel task either. 
When the array length reaches a minimum granularity and you got more than 1 worker thread, the array is sorted using the parallel sort method. And the ForkJoin common pool is used to execute parallel tasks here. 
Reference : http://download.java.net/lambda/b84/docs/api/java/util/Arrays.html#parallelSort%28int 



Next Article
Parallel vs Sequential Stream in Java

S

Saumya Mishra
Improve
Article Tags :
  • Algorithms
  • DSA
  • Java
  • Technical Scripter
Practice Tags :
  • Algorithms
  • Java

Similar Reads

  • Parallel vs Sequential Stream in Java
    Prerequisite: Streams in Java A stream in Java is a sequence of objects which operates on a data source such as an array or a collection and supports various methods.  It was introduced in Java 8's java.util.stream package. Stream supports many aggregate operations like filter, map, limit, reduce, f
    5 min read
  • What is Java Parallel Streams?
    Java Parallel Streams is a feature of Java 8 and higher, meant for utilizing multiple cores of the processor. Normally any Java code has one stream of processing, where it is executed sequentially. Whereas by using parallel streams, we can divide the code into multiple streams that are executed in p
    3 min read
  • Parallel Data Processing in Java | Set 1
    We know that new Stream in Java (introduced in Java 8) interface let us manipulate collections of data in a declarative way. In this topic, we will discover how the Stream interface gives us the opportunity to execute operations in parallel on a collection of data without much effort. It lets us dec
    2 min read
  • Reverse elements of a Parallel Stream in Java
    Given a Parallel Stream in Java, the task is to reverse its elements. Examples: Input: Parallel Stream = {11, 22, 33, 44} Output: {44, 33, 22, 11} Input: Parallel Stream = {a, b, c, d} Output: {d, c, b, a} Below are the various ways to do so: Using Collectors class : Since Streams in Java don't stor
    3 min read
  • Parallel Count Sort
    What is Parallel Count Sort?Parallel count sort is an efficient algorithm that sorts an array of elements in a parallel manner. It is a variation of the classic count sort algorithm which is used to sort a collection of objects based on their frequency. The algorithm is based on the idea of counting
    12 min read
  • How to sort an Array in C# | Array.Sort() Method | Set – 5
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort<TKey, TValue>(TKey[], TValue[], IComparer<TKey>) Method This method sorts a pair of array objects based on the
    7 min read
  • How to sort an Array in C# | Array.Sort() Method Set – 2
    Array.Sort Method is used to sort elements in a one-dimensional array. There are 17 methods in the overload list of this method. Here we will discuss the following methods: Sort(Array, Int32, Int32, IComparer) Method Sort(Array, Array, Int32, Int32, IComparer) Method Sort(Array, Int32, Int32) Method
    9 min read
  • Stream sorted() in Java
    Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously s
    2 min read
  • Tag Sort (To get both sorted and original)
    This is not a new sorting algorithm, but an idea when we need to avoid swapping of large objects or need to access elements of a large array in both original and sorted orders. A common sorting task is to sort elements of an array using a sorting algorithm like Quick Sort, Bubble Sort.. etc, but the
    10 min read
  • IntStream parallel() in Java
    IntStream parallel() is a method in java.util.stream.IntStream. This method returns a parallel IntStream, i.e, it may return itself, either because the stream was already present, or because the underlying stream state was modified to be parallel. IntStream parallel() is an intermediate operation. T
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences