Question

I have a multithreaded java sorting program that works as follows: 1. A list of double...

I have a multithreaded java sorting program that works as follows:

1. A list of double values is divided into two smaller lists of equal size

2. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice

3. The two sublists are then merged by a third thread merging thread that merges the two sublists into a single sorted list.

SIMPLE EXECUTION

>java SortParallel 1000
Sorting is done in 8.172561ms when two threads are used
Sorting is done in 8.044095ms when one thread is used


I need to extend my program so it can take another command line parameter, T (an even integer). Then it creates T threads instead of just 2 and gives 1/T of the array to each thread to sort and then merge! And see how increasing the number of threads affects the execution time.

Here is existing code:

/* SortParallel.java */
import java.util.*;

class MergeThread extends Thread {
private double[] in ; // the input array
private double[] out; // the output array
private int mid; // dividing point into subarrays

public MergeThread(double[] i, double[] o, int m) { in = i;
out = o;
mid = m;
}

public void run() {
int i, j, k;
//System.out.println("Merge " + in.length + " : ");
i = k = 0;
j = mid;
while (i < mid && j < in .length) {
if ( in [i] < in [j])
out[k++] = in [i++];
else
out[k++] = in [j++];
}
while (i < mid)
out[k++] = in [i++];
while (j < in .length)
out[k++] = in [j++];
/*for(i = 0; i < in.length; i++)
System.out.print(" " + out[i]);
System.out.println(""); */
}
};

class SortThread extends Thread {
private double[] arr; // the array to be sorted
private int beg, end; // The start, end points in the array to be sorted

public SortThread(double[] a, int b, int e) {
arr = a;
beg = b;
end = e;
}

public void run() {
int i, j, min;
double tmp;
arr = arr;
//System.out.println("sort " + beg + " to " + end);
for (i = beg; i < end; i++) {
min = i;
for (j = i + 1; j < end; j++) {
if (arr[j] < arr[min])
min = j;
}
tmp = arr[i];
arr[i] = arr[min];
arr[min] = tmp;
}
/*for(i = beg; i < end; i++)
System.out.print(" " + arr[i]);
System.out.println("\nEnd sort"); */
}
};
public class SortParallel {

public static void main(String[] arg) {
int mid, N, i;

double[] arr; /* array */
double[] arr2; /* Used for a copy */
double[] merged; /* For storing the merged array */

long start, diff;
/* I NEED ONE EXTRA PARAMETER HERE */
if (arg.length != 1) {
System.out.println("Usage: java SortParallel ");
return;
}

N = Integer.parseInt(arg[0]);
arr = new double[N];
arr2 = new double[N];
merged = new double[N];

Random rand = new Random(System.currentTimeMillis());

//System.out.println ("Array: ");
for (i = 0; i < N; i++) {
/* generate random numbers */
arr[i] = arr2[i] = rand.nextDouble() * 99.0 + 1.0; /* range 1.0 - 100.0 */
//System.out.print(" "+ arr[i]);
}
//System.out.println("");

//Create threads
SortThread sort1 = new SortThread(arr, 0, N / 2);
SortThread sort2 = new SortThread(arr, N / 2, arr.length);
MergeThread merge1 = new MergeThread(arr, merged, N / 2);

start = System.nanoTime(); /* start time */

/* Start the threads for working on sub arrays */
sort1.start();
sort2.start();

/* Wait for sorting to complete */
try {
sort1.join();
sort2.join();
} catch (Exception e) {
e.printStackTrace();
}

/* Start thread for merge */
merge1.start();
/* Wait for merge thread to complete */
try {
merge1.join();
} catch (Exception e) {
e.printStackTrace();
}

diff = System.nanoTime() - start; /* End time */

System.out.println("Sorting is done in " + diff / 1000000.0f + "ms when two threads are used");

SortThread sortComplete = new SortThread(arr2, 0, N); /* To run on the whole array */

start = System.nanoTime(); /* start time */

sortComplete.start();
try {
sortComplete.join();
} catch (Exception e) {
e.printStackTrace();
}

diff = System.nanoTime() - start; /* End time */

System.out.println("Sorting is done in " + diff / 1000000.0f + "ms when one thread is used");
}
}

Please do the needful.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

> <terminated> SortParallel [Java Application] C:\Program Files\ava\jdk1. Sorting is done in 0.6813ms when 4 threads are used

import java.util.*;

class MergeThread extends Thread {
    private double[] in; // the input array
    private double[] out; // the output array
    private int mid, start, end; // dividing point into subarrays

    public MergeThread(double[] i, double[] o, int start, int mid, int end) {
        in = i;
        out = o;
        this.start = start;
        this.mid = mid;
        this.end = end;
    }

    public void run() {
        int i, j, k;
        i = k = start;
        j = mid;
        while (i < mid && j < end) {
            if (in[i] < in[j])
                out[k++] = in[i++];
            else
                out[k++] = in[j++];
        }
        while (i < mid)
            out[k++] = in[i++];
        while (j < end)
            out[k++] = in[j++];
    }
};

class SortThread extends Thread {
    private double[] arr; // the array to be sorted
    private int beg, end; // The start, end points in the array to be sorted

    public SortThread(double[] a, int b, int e) {
        arr = a;
        beg = b;
        end = e;
    }

    public void run() {
        int i, j, min;
        double tmp;

        for (i = beg; i < end; i++) {
            min = i;
            for (j = i + 1; j < end; j++) {
                if (arr[j] < arr[min])
                    min = j;
            }
            tmp = arr[i];
            arr[i] = arr[min];
            arr[min] = tmp;
        }
    }
};

public class SortParallel {

    public static void main(String[] arg) {
        int arrSize, i;
        int numThreads;
        
        double[] arr; /* array */
        double[] merged; /* For storing the merged array */

        long start, diff;

        /* I NEED ONE EXTRA PARAMETER HERE */
        if (arg.length != 2) {
            System.out.println("Usage: java SortParallel <ArraySize> <NumThreads>");
            return;
        }

        // numThreads should be a power of 2, and Similarly, the array size should be divisible by numThreads
        arrSize = Integer.parseInt(arg[0]);
        numThreads = Integer.parseInt(arg[1]);

        arr = new double[arrSize];
        merged = new double[arrSize];

        Random rand = new Random(System.currentTimeMillis());

        for (i = 0; i < arrSize; i++) {
            arr[i] = rand.nextDouble() * 99.0 + 1.0; /* range 1.0 - 100.0 */
        }
        
        int subSize = arrSize / numThreads;

        SortThread threads[] = new SortThread[numThreads];
        int startIndex = 0;
        for (i = 0; i < numThreads - 1; i++) {
            threads[i] = new SortThread(arr, startIndex, startIndex + subSize);
            threads[i].start();
            startIndex += subSize;
        }
        threads[i] = new SortThread(arr, startIndex, arrSize);
        threads[i].start();

        start = System.nanoTime(); /* start time */
        // Now array is sorted.

        // wait for threads to join.
        for (i = 0; i < numThreads; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        int threadCount = numThreads;
        while(threadCount != 1) {
            threadCount = threadCount/2;
            MergeThread mergeThreads[] = new MergeThread[threadCount];
            
            startIndex = 0;
            for (i = 0; i < threadCount; i++) {
                if(i != threadCount-1) {
                    mergeThreads[i] = new MergeThread(arr, merged, startIndex, startIndex + subSize, startIndex + 2*subSize);
                } else {
                    mergeThreads[i] = new MergeThread(arr, merged, startIndex, startIndex + subSize, arr.length);
                }
                startIndex += 2 * subSize;
            }
            
            for (i = 0; i < threadCount; i++) {
                mergeThreads[i].start();
            }
            
            // switch arr and merged, as we need a temporary array to copy the data back.
            double tmp[] = arr;
            arr = merged;
            merged = tmp;
            subSize = subSize * 2;
        }
        
        // Uncomment below to see the array
        // System.out.println(Arrays.toString(arr));

        diff = System.nanoTime() - start; /* End time */

        System.out.println("Sorting is done in " + diff / 1000000.0f + "ms when " + numThreads + " threads are used");
    }
}

**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.

Add a comment
Know the answer?
Add Answer to:
I have a multithreaded java sorting program that works as follows: 1. A list of double...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a multithreaded sorting program that works as follows: A list of integers is divided into...

    Write a multithreaded sorting program that works as follows: A list of integers is divided into two smaller lists of equal size. Two separate threads (which we will term sorting threads) sort each sublist using a sorting algorithm of your choice. The two sublists are then merged by a third thread—a merging thread —which merges the two sublists into a single sorted list. Because global data are shared cross all threads, perhaps the easiest way to set up the data...

  • I need to program 3 and add to program 2 bellows: Add the merge sort and...

    I need to program 3 and add to program 2 bellows: Add the merge sort and quick sort to program 2 and do the same timings, now with all 5 sorts and a 100,000 element array. Display the timing results from the sorts. DO NOT display the array. ____________________>>>>>>>>>>>>>>>>>>>>___________________________ (This is program 2 code that I did : ) ---->>>>>> code bellow from program 2 java program - Algorithms Write a program that randomly generates 100,000 integers into an array....

  • Sorting Threads Assignment Overview Write a multithreaded sorting program in Java which uses the ...

    Sorting Threads Assignment Overview Write a multithreaded sorting program in Java which uses the merge sort algorithm. The basic steps of merge sort are: 1) divide a collection of items into two lists of equal size, 2) use merge sort to separately sort each of the two lists, and 3) combine the two sorted lists into one sorted list. Of course, if the collection of items is just asingle item then merge sort doesn’t need to perform the three steps,...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • On the following code there is an error bc you are not reverting back to the...

    On the following code there is an error bc you are not reverting back to the original order after a sort. For the next sort you are passing the same reference variable to the next method. But that will point to the same (already sorted) array on the memory. Hence after the first sorting method, all three sorting methods are working on the already sorted array. Do the following : Just copy each data set to 4 different arrays -...

  • Please help me to solve the problem with java language! An implementation of the Merge Sort...

    Please help me to solve the problem with java language! An implementation of the Merge Sort algorithm. Modify the algorithm so that it splits the list into 3 sublists (instead of two). Each sublist should contain about n/3 items. The algorithm should sort each sublist recursively and merge the three sorted sublists. The traditional merge sort algorithm has an average and worst-case performance of O(n log2 n). What is the performance of the 3-way Merge Sort algorithm? Merge Sort algorithm...

  • USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list...

    USE JAVA PROGRAMMING Create a program that would collect list of persons using double link list and use a Merge Sort to sort the object by age. Create a class called Person : name and age Create methods that add, and delete Person from the link list Create a method that sorts the persons' objects by age. package mergesort; public class MergeSortExample { private static Comparable[] aux; // auxiliary array for merges public static void sort(Comparable[] a) { aux =...

  • The following code is a Java code for insertion sort. I would like this code to...

    The following code is a Java code for insertion sort. I would like this code to be modified by not allowing more than 10 numbers of integer elements (if the user enters 11 or a higher number, an error should appear) and also finding the range of the elements after sorting. /* * Java Program to Implement Insertion Sort */ import java.util.Scanner; /* Class InsertionSort */ public class InsertionSortTwo { /* Insertion Sort function */ public static void sort( int...

  • use the same code. but the code needs some modifications. so use this same code and...

    use the same code. but the code needs some modifications. so use this same code and modify it and provide a output Java Program to Implement Merge Sort import java.util.Scanner Class MergeSort public class MergeSort Merge Sort function / public static yoid sortfintfl a, int low, int high) int N-high-low; if (N1) return; int mid- low +N/2; Il recursively sort sort(a, low, mid); sort(a, mid, high); I/ merge two sorted subarrays int] temp new int[N]; int i- low, j-mid; for...

  • the code needs to be modifed. require a output for the code Java Program to Implement...

    the code needs to be modifed. require a output for the code Java Program to Implement Insertion Sort import java.util.Scanner; /Class InsertionSort * public class Insertion Sort { /Insertion Sort function */ public static void sort( int arr) int N- arr.length; int i, j, temp; for (i-1; i< N; i++) j-i temp arrli; while (j> 0 && temp < arrli-1) arrli]-arrli-1]; j-j-1; } arrlj] temp; /Main method * public static void main(String [] args) { Scanner scan new Scanner( System.in...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT