#include <iostream>
#include <vector>
#include <algorithm>
#include <thread>
#include <chrono>
#include <random>
#include <cstddef>
const size_t THRESHOLD = 4096; // Threshold for switching to sequential sort to limit thread creation overhead
/**
* Parallel merge sort implementation using std::thread.
* Recursively divides the array into two halves, sorts them in parallel,
* and merges the sorted halves using std::inplace_merge.
*
* @param a Reference to the vector to sort
* @param l Left index of the subarray
* @param r Right index of the subarray
*/
void parallel_merge_sort(std::vector<int>& a, size_t l, size_t r) {
if (l >= r) {
return;
}
// Base case: small subarrays are sorted sequentially to avoid thread overhead
if (r - l + 1 <= THRESHOLD) {
std::sort(a.begin() + l, a.begin() + r + 1);
return;
}
size_t m = l + (r - l) / 2;
// Spawn two threads for the two halves
std::thread t1(parallel_merge_sort, std::ref(a), l, m);
std::thread t2(parallel_merge_sort, std::ref(a), m + 1, r);
// Wait for both halves to be sorted
t1.join();
t2.join();
// Merge the two sorted halves in-place
std::inplace_merge(a.begin() + l, a.begin() + m + 1, a.begin() + r + 1);
}
int main() {
const size_t N = 10'000'000; // 10 million elements for demo
// Generate random data
std::vector<int> a(N);
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(0, N);
for (auto& x : a) {
x = dis(gen);
}
std::cout << "Sorting " << N << " random integers using parallel merge sort..." << std::endl;
auto start = std::chrono::high_resolution_clock::now();
parallel_merge_sort(a, 0, N - 1);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed = end - start;
// Verify sorted
bool is_sorted = std::is_sorted(a.begin(), a.end());
std::cout << "Time elapsed: " << elapsed.count() << " seconds" << std::endl;
std::cout << "Array is sorted: " << (is_sorted ? "YES" : "NO") << std::endl;
// Optional: Compare with std::sort for benchmarking (uncomment to use)
/*
std::vector<int> b = a; // Copy for sequential sort
auto seq_start = std::chrono::high_resolution_clock::now();
std::sort(b.begin(), b.end());
auto seq_end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> seq_elapsed = seq_end - seq_start;
std::cout << "Sequential std::sort time: " << seq_elapsed.count() << " seconds" << std::endl;
std::cout << "Speedup: " << seq_elapsed.count() / elapsed.count() << "x" << std::endl;
*/
return 0;
}
Key Features:
Parallelism: Uses std::thread to sort left and right halves concurrently.
Threshold: Switches to sequential std::sort for small subarrays (THRESHOLD = 4096) to minimize thread creation overhead.
Merging: std::inplace_merge efficiently merges sorted halves without extra space.
Demo: Generates 10M random integers, times the sort, and verifies correctness.