0% found this document useful (0 votes)
6 views2 pages

Merge Sort

The document presents a C++ implementation of the Merge Sort algorithm, which sorts an array of random integers. It generates an array of 10,000 random integers, sorts them using the mergeSort function, and measures the execution time of the sorting process. The output includes the original and sorted arrays, along with the time taken for execution.

Uploaded by

yaseeniqbal365
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Merge Sort

The document presents a C++ implementation of the Merge Sort algorithm, which sorts an array of random integers. It generates an array of 10,000 random integers, sorts them using the mergeSort function, and measures the execution time of the sorting process. The output includes the original and sorted arrays, along with the time taken for execution.

Uploaded by

yaseeniqbal365
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

2.

Parallel Merge Sort using OpenMP

#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;

vector<int> mergeSort(vector<int>& arr) {


int n = arr.size();
if (n <= 1) return arr;

int mid = n / 2;
vector<int> left(arr.begin(), arr.begin() + mid);
vector<int> right(arr.begin() + mid, arr.end());

left = mergeSort(left);
right = mergeSort(right);

// Merge
vector<int> merged;
int i = 0, j = 0;
while (i < left.size() && j < right.size()) {
if (left[i] <= right[j])
merged.push_back(left[i++]);
else
merged.push_back(right[j++]);
}
while (i < left.size()) merged.push_back(left[i++]);
while (j < right.size()) merged.push_back(right[j++]);

return merged;
}

int main() {
vector<int> arr(10000);
for (int i = 0; i < 10000; i++) {
arr[i] = rand() % 100;
}

cout << "Original array: [";


for (int i = 0; i < 10; i++) cout << arr[i] << " ";
cout << "...]\n";

clock_t start = clock();


vector<int> sortedArr = mergeSort(arr);
clock_t end = clock();

cout << "Sorted array: [";


for (int i = 0; i < 10; i++) cout << sortedArr[i] << " ";
cout << "...]\n";

double time_taken = double(end - start) / CLOCKS_PER_SEC;


cout << "Execution time: " << time_taken << " seconds\n";

return 0;
}

Output:
Original array: [83 86 77 15 93 35 86 92 49 21 ...]
Sorted array: [0 0 0 0 0 0 0 0 0 0 ...]
Execution time: 0.013583 seconds

You might also like