Question

In: Computer Science

Implement Quicksort in Java by sorting in parallel after partitioning; for this, the parent thread can...

Implement Quicksort in Java by sorting in parallel after partitioning; for this, the parent thread can continue sorting one segment and a child thread is created for sorting the other segment. However, create a new thread only if both segments contain more than S elements, otherwise sort sequentially both segments.

%%writefile Quicksort.java
import java.util.Random;

YOUR CODE HERE

public class Quicksort {

    static int N;   // number of elements to be sorted
    static int S;   // threshold for creating a sub-thread
    static int a[]; // array to be sorted

    static int partition(int p, int r) {
        int x = a[r];
        int i = p - 1;
        for (int j = p; j <= r - 1; j++) {
            if (a[j] <= x) {
                i++; 
                int t = a[i]; a[i] = a[j]; a[j] = t;
            }
        }
        int t = a[i + 1]; a[i + 1] = a[r]; a[r] = t;
        return i + 1;
    }

    static void sequentialsort(int p, int r) {
        if (p < r) {
            int q = partition(p, r);
            sequentialsort(p, q - 1);
            sequentialsort(q + 1, r);
        }
    }

YOUR CODE HERE

    public static void main(String args[]) {
        N = Integer.parseInt(args[0]);
        S = Integer.parseInt(args[1]);
        a = new int[N + 1];
        Random random = new Random();
        for (int i = 0; i < N; i++) a[i] = random.nextInt(10000);
        final long start = System.currentTimeMillis();

        parallelsort(0, N - 1);

        final long end = System.currentTimeMillis();
        for (int i = 1; i < N; i++) assert a[i - 1] <= a[i];
        System.out.println((end - start) + " ms");
    }
}

Above code only defines sequential sorting. Copy it and add parallel sorting; your solution must be derived from above template by adding code at the two marked locations.

Use the commands below to test your implementation.

!javac Quicksort.java
!java -enableassertions Quicksort 100000 10

Solutions

Expert Solution

import java.io.*;

import java.util.Random;

import java.util.concurrent.ForkJoinPool;

import java.util.concurrent.RecursiveTask;

public class QuickSortMutliThreading

    extends RecursiveTask<Integer> {

    int start, end;

    int[] arr;

    /**

     * Finding random pivoted and partition

     * array on a pivot.

     * There are many different

     * partitioning algorithms.

     * @param start

     * @param end

     * @param arr

     * @return

     */

    private int partion(int start, int end,

                        int[] arr)

    {

        int i = start, j = end;

        // Decide random pivot

        int pivote = new Random()

                         .nextInt(j - i)

                     + i;

        // Swap the pivote with end

        // element of array;

        int t = arr[j];

        arr[j] = arr[pivote];

        arr[pivote] = t;

        j--;

        // Start partioning

        while (i <= j) {

            if (arr[i] <= arr[end]) {

                i++;

                continue;

            }

            if (arr[j] >= arr[end]) {

                j--;

                continue;

            }

            t = arr[j];

            arr[j] = arr[i];

            arr[i] = t;

            j--;

            i++;

        }

        // Swap pivote to its

        // correct position

        t = arr[j + 1];

        arr[j + 1] = arr[end];

        arr[end] = t;

        return j + 1;

    }

    // Function to implement

    // QuickSort method

    public QuickSortMutliThreading(int start,

                                   int end,

                                   int[] arr)

    {

        this.arr = arr;

        this.start = start;

        this.end = end;

    }

    @Override

    protected Integer compute()

    {

        // Base case

        if (start >= end)

            return null;

        // Find partion

        int p = partion(start, end, arr);

        // Divide array

        QuickSortMutliThreading left

            = new QuickSortMutliThreading(start,

                                          p - 1,

                                          arr);

        QuickSortMutliThreading right

            = new QuickSortMutliThreading(p + 1,

                                          end,

                                          arr);

        // Left subproblem as separate thread

        left.fork();

        right.compute();

        // Wait untill left thread complete

        left.join();

        // We don't want anything as return

        return null;

    }

    // Driver Code

    public static void main(String args[])

    {

        int n = 7;

        int[] arr = { 54, 64, 95, 82, 12, 32, 63 };

        // Forkjoin ThreadPool to keep

        // thread creation as per resources

        ForkJoinPool pool

            = ForkJoinPool.commonPool();

        // Start the first thread in fork

        // join pool for range 0, n-1

        pool.invoke(

            new QuickSortMutliThreading(

                0, n - 1, arr));

        // Print shorted elements

        for (int i = 0; i < n; i++)

            System.out.print(arr[i] + " ");

    }

}


Related Solutions

IN JAVA Implement Quicksort with ‘median-of-three’ partitioning You should be able to test a 1000, 10000...
IN JAVA Implement Quicksort with ‘median-of-three’ partitioning You should be able to test a 1000, 10000 and 10000 length array with inters spanning from 1 to 10,000. You cannot use functions from standard libraries implementing Quicksort.
The purpose here is to implement the QuickSort sorting algorithm to sort integers. Write a C...
The purpose here is to implement the QuickSort sorting algorithm to sort integers. Write a C program which accepts 1 command-line argument: the name of a text file which contains integers, one-per line. Your C program must be named project3. Your C program needs to implement the QuickSort algorithm to sort the integers read from the file specified on the command-line. Your QuickSort implementation must utilize the median-of-three algorithm for choosing a pivot, and BubbleSort any sub arrays with less...
Can someone implement the following in Java? Quicksort with switching to Insertion sort when the number...
Can someone implement the following in Java? Quicksort with switching to Insertion sort when the number of elements in the subarray is less than or equal to 2% of the original number Requirements: 1) functions from standard libraries implementing Quicksort are NOT allowed;
C++ Program 2–Implement a Priority queue using a SORTED list. Use Quicksort after adding a new...
C++ Program 2–Implement a Priority queue using a SORTED list. Use Quicksort after adding a new node.Example of quick sort below. Adopt to your program. #include <iostream> voidquickSort(inta[], intfirst, intlast); intpivot(inta[], intfirst, intlast); voidswap(int& a, int& b); voidswapNoTemp(int& a, int& b); voidprint(intarray[], constint& N); usingnamespacestd; intmain() { inttest[] = { 7, -13, 1, 3, 10, 5, 2, 4 }; intN = sizeof(test)/sizeof(int); cout << "Size of test array :"<< N << endl; cout << "Before sorting : "<< endl; print(test,...
4 Implement a Java program that meets the following requirements • You can use the Java...
4 Implement a Java program that meets the following requirements • You can use the Java standard sequence data structure API types for sets, lists, stack,queue and priority queue as needed. All are available in the java.util package, which you will want to import in your program. 1. Argue in code comments which data structure, stack or queue, you will use to implement this method. Implement a method which creates some String objects as food orders for a small restaurant,...
in JAVA: implement a class called tree (from scratch) please be simple so i can understand...
in JAVA: implement a class called tree (from scratch) please be simple so i can understand thanks! tree(root) node(value, leftchild,rightchild) method: insert(value)
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT