Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
15 views1 page

Merge

The document contains a C++ program that implements the merge sort algorithm using OpenMP for parallel processing. It prompts the user to input the number of elements and the elements themselves, sorts them using the merge sort function, and then outputs the sorted array. The program dynamically allocates memory for the arrays used in the sorting process and ensures proper memory management by deleting allocated memory.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views1 page

Merge

The document contains a C++ program that implements the merge sort algorithm using OpenMP for parallel processing. It prompts the user to input the number of elements and the elements themselves, sorts them using the merge sort function, and then outputs the sorted array. The program dynamically allocates memory for the arrays used in the sorting process and ensures proper memory management by deleting allocated memory.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

#include <iostream>

#include <omp.h>
using namespace std;
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1; // Size of left array
int n2 = r - m; // Size of right array
int* left = new int[n1];
int* right = new int[n2];
for (int i = 0; i < n1; i++)
left[i] = arr[l + i];
for (int j = 0; j < n2; j++)
right[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2)
arr[k++] = (left[i] <= right[j]) ? left[i++] : right[j++];
while (i < n1) arr[k++] = left[i++];
while (j < n2) arr[k++] = right[j++];
delete[] left;
delete[] right; }
void mergeSort(int *arr, int low, int high) {
if (low < high) {
int mid = (low + high) / 2;
#pragma omp parallel sections
{
#pragma omp section
mergeSort(arr, low, mid);
#pragma omp section
mergeSort(arr, mid + 1, high);
}
merge(arr, low, mid, high);}}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int* arr = new int[n];
cout << "Enter " << n << " elements:\n";
for (int i = 0; i < n; ++i)
cin >> arr[i];
mergeSort(arr, 0, n - 1);
cout << "Sorted array:\n";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
delete[] arr;
return 0;
}

You might also like