Question

In: Computer Science

Using the template given in ParallelMergeSort.c write the functions to divide the original array into equal...

Using the template given in ParallelMergeSort.c write the functions to divide the original array into equal fractions given the number of threads and perform Parallel MergeSort pThreads. Your algorithm should work for 2 threads.

ParallelMergeSort.c

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

#define SIZE 100

int array[SIZE];

void fillArrayWithRandomNumbers(int arr[SIZE]) {
for(int i = 0; i<SIZE; i++) array[i] = rand()%100;
}

void printArray(int arr[SIZE]) {
for(int i = 0; i<SIZE; i++) printf("%5d", arr[i]);
printf("\n");
}

typedef struct StartEndIndexes {
int start;
int end;
} StartEndIndexes;

// Runs mergesort on the array segment described in the argument. Spawns two threads to mergesort each half
// of the array segment, and then merges the results.
void* mergeSort(void* args) {

// Please fill this out!
return NULL;
}

int main() {
srand(time(0));
StartEndIndexes sei;
sei.start = 0;
sei.end = SIZE - 1;
  
// 1. Fill array with random numbers.
fillArrayWithRandomNumbers(array);
  
// 2. Print the array.
printf("Unsorted array: ");
printArray(array);
  
// 3. Create a 2 threads for merge sort.
  
// 4. Wait for mergesort to finish.
  

// 5. Print the sorted array.
printf("Sorted array: ");
printArray(array);
}

Pease fill out bolded sections!

Solutions

Expert Solution

Working code implemented in C and appropriate comments provided for better understanding.

Source Code:

#include <stdio.h>

#include <pthread.h>

#include <stdlib.h>

#include <time.h>

#include <unistd.h>

#define SIZE 5

int array[SIZE];

void fillArrayWithRandomNumbers(int array[SIZE]) {

for(int i = 0; i<SIZE; i++) array[i] = rand()%100;

}

void printArray(int array[SIZE]) {

for(int i = 0; i<SIZE; i++) printf("%5d", array[i]);

printf("\n");

}

typedef struct StartEndIndexes {

int start;

int end;

} StartEndIndexes;


// Merges array subproblems into fully sorted array

void merge(int l, int m, int r)

{

int i, j, k;

int n1 = m - l + 1;

int n2 = r - m;

/* create temp arrays */

int L[n1], R[n2];

/* Copy data to temp arrays L[] and R[] */

for (i = 0; i < n1; i++)

L[i] = array[l + i];

for (j = 0; j < n2; j++)

R[j] = array[m + 1+ j];

/* Merge the temp arrays back into arr[l..r]*/

i = 0; // Initial index of first subarray

j = 0; // Initial index of second subarray

k = l; // Initial index of merged subarray

while (i < n1 && j < n2)

{

if (L[i] <= R[j])

{

array[k] = L[i];

i++;

}

else

{

array[k] = R[j];

j++;

}

k++;

}

/* Copy the remaining elements of L[], if there

are any */

while (i < n1)

{

array[k] = L[i];

i++;

k++;

}

/* Copy the remaining elements of R[], if there

are any */

while (j < n2)

{

array[k] = R[j];

j++;

k++;

}

}

// Runs mergesort on the array segment described in the

// argument. Spawns two threads to mergesort each half

// of the array segment, and then merges the results.

void* mergeSort(void* args) {

// Dereference args

StartEndIndexes sei = *((StartEndIndexes*)args);

int error1, error2, midpoint;

// Check for base case

if (sei.start < sei.end)

{

// Find the midpoint

midpoint = (sei.start + sei.end) / 2;

// Create variables for subproblems

StartEndIndexes sei1, sei2;

sei1.start = sei.start;

sei1.end = midpoint;

sei2.start = midpoint + 1;

sei2.end = sei.end;

pthread_t left_tid, right_tid;

// Call threads to sort both subproblems

error1 = pthread_create(&left_tid, NULL, mergeSort, &sei1);

error2 = pthread_create(&right_tid, NULL, mergeSort, &sei2);

if (error1 != 0)

printf("Error sorting left tree.\n");

if (error2 != 0)

printf("Error sorting right tree.\n");

error1 = pthread_join(left_tid, NULL);

error2 = pthread_join(right_tid, NULL);

if (error1 != 0)

printf("Error sorting left tree.\n");

if (error2 != 0)

printf("Error sorting right tree.\n");

// Combine subproblems to form solution

merge(sei.start, midpoint, sei.end);

}

return NULL;

}

int main() {

srand(time(0));

StartEndIndexes sei;

sei.start = 0;

sei.end = SIZE - 1;

int error;

// 1. Fill array with random numbers.

fillArrayWithRandomNumbers(array);

// 2. Print the array.

printf("Unsorted array: ");

printArray(array);

// 3. Create a thread for merge sort.

pthread_t tid;

error = pthread_create(&(tid), NULL, &mergeSort, &sei);

if (error != 0)

printf("Error creating thread.\n");

// 4. Wait for mergesort to finish.

error = pthread_join(tid, NULL);

if (error != 0)

printf("Error joining thread.\n");

// 5. Print the sorted array.

printf("Sorted array: ");

printArray(array);

}

Sample Output Screenshots:


Related Solutions

Using the template given in ParallelMergeSort.c write the functions to divide the original array into equal...
Using the template given in ParallelMergeSort.c write the functions to divide the original array into equal fractions given the number of threads and perform Parallel MergeSort pThreads. Your algorithm should work for 2 threads. ParallelMergeSort.c #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <time.h> #include <unistd.h> #define SIZE 100 int array[SIZE]; void fillArrayWithRandomNumbers(int arr[SIZE]) { for(int i = 0; i<SIZE; i++) array[i] = rand()%100; } void printArray(int arr[SIZE]) { for(int i = 0; i<SIZE; i++) printf("%5d", arr[i]); printf("\n"); } typedef struct...
Given an array ? of ? integers. Divide ? into three subsets such that the total...
Given an array ? of ? integers. Divide ? into three subsets such that the total absolute difference of subset sums between them is minimum. Provide python source code, time complexity, and pseudocode. thank you
Given the following array, write a program in C++ to sort the array using a selection...
Given the following array, write a program in C++ to sort the array using a selection sort and display the number of scores that are less than 500 and those greater than 500. Scores[0] = 198 Scores[3] = 85 Scores[6] = 73 Scores[9] = 989 Scores[1] = 486 Scores[4] = 216 Scores[7] = 319 Scores[2] = 651 Scores[5] = 912 Scores[8] = 846
Write recursive method to return true if a given array has element equal to employee emp,...
Write recursive method to return true if a given array has element equal to employee emp, or returns false otherwise. Array can be empty or not. //PRECONDITION: Varible n denotes the number of occupied positions in the array and must be non-negative. Employee class has method getSalary() that returns employee's salary, // and it has method boolean equals(Employee emp) that accept an employee object and returns true if employee calling the equals method is equal as employee emp, and returns...
Using the implementation of the array based list given, write a CLIENT method (that is NOT...
Using the implementation of the array based list given, write a CLIENT method (that is NOT part of the class) called replace, that given a value and a position replaces the value of the element at that position. REMEMBER error checking public static void replace( List aList, int newValue, int position) public class ArraybasedList implements MyListInterface{ private static final int DEFAULTSIZE = 25; // Data members: private int currentSize; private int maxSize; private S[] elements; //default constructor has NO parameters...
Write a method called splitArray which will receive four parameters as follows: Original array Array of...
Write a method called splitArray which will receive four parameters as follows: Original array Array of multiples Array of not multiples Number to compare if the values within the original array are multiples of Assuming that always the original array will contain half values as multiples and half as not multiples. Your method should return the numbers within the original array that are multiples of the last parameter in the array of multiples (second parameter). Furthermore, your method should return...
Write a program using multiple functions. Make use of an array to store data Make use...
Write a program using multiple functions. Make use of an array to store data Make use of searching techniques Read data from a file Write data to a file Instructions: In this lab, you will be examining a set of stock collected over a twenty four day period. Be sure to make use of an array to store these stocks. You will be required to read in the data points from a file. Write a function to read in the...
Given an array of integers, and given a specific value k (not equal to 0), produce...
Given an array of integers, and given a specific value k (not equal to 0), produce all unique pairs of values in the array which differ by k. For example, if the array has [1,4,9,12, 6, 15, 5, 13,17] and k=3, the answer would be (1,4 ) ( 9,12), ( 9,6), (12,15). If k=4, the answer would be (1,5), (9,5), (13,17), (9.13). Notice that you do not print the same answer twice, for instance (9,13), and (13,9).
Please write a C++ program. Please rewrite your Array (including the operator overloading) into a template....
Please write a C++ program. Please rewrite your Array (including the operator overloading) into a template. And rewrite your main function to test your template for integer array and double array. Following is my complete code: #include <iostream> using namespace std; class Array { private: // Pointer to memory block to store integers int* data; // Maximum size of memory block int cap; // Stores number of integers in an array int num; public: // Constructor Array(int size); // Default...
Write a program in Java to sort the given array using merge sort, quick sort, insertion...
Write a program in Java to sort the given array using merge sort, quick sort, insertion sort, selection sort and bubble sort based on the input from the user which sorting technique they wanted to use. Get the array size, array elements from the user, and also display the sorted array along with the name of the sorting technique used.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT