Write a concurrent merge sort where k threads are used to pa

Write a concurrent merge sort, where k threads are used to partition the array of n integers. We can assume that kx = n. Each of the k threads will use insertion sort to actually sort the k partitions. A merge thread will then merge the k parts into a sorted array of size n.

Solution

#include <iostream>
#include <thread>
#include <vector>
using namespace std;
void merge(vector<int>& vec, int s, int m, int e)
{
    vector<int> one (vec.begin() + start, vec.begin() + m + 1);
    vector<int> two (vec.begin() + mid + 1, vec.begin() + e + 1);
    int a = 0;
    int b = 0;
    int index = s;
    while (a < one.size() && b < two.size())
    {
        if (one[a] < two[b])
            vec[index ++] = one[a ++];
        else
            vec[index ++] = two[b ++];
    }

    // merge the left-over elements
    while (a < one.size())
        vec[index ++] = one[a ++];
    while (b < two.size())
        vec[index ++] = two[b ++];
}

void merge_sort(vector<int>& vec, int s, int e)
{
if (s >= e)
    return;

int m = s+ (e - s) / 2;
// multi-thread version
thread first(merge_sort, std::ref(vec), s, m);
thread second(merge_sort, std::ref(vec), m + 1, e);
first.join();
second.join();

merge(vec, s, m, e);
}
int main()
{
    int a[] ;
    int n;
    cin>>\"enter length of the array: \">>n;
     for(i=0; i<n;i++)
     {
         cin>>a[i];
      }
    vector<int> vec(a, a + n);
    merge_sort(vec, 0, n-1);
    for (int i = 0; i < n; i ++)
        cout << vec[i] << endl;
    return 0;
}

 Write a concurrent merge sort, where k threads are used to partition the array of n integers. We can assume that kx = n. Each of the k threads will use inserti

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site