实现归并排序的openmp程序
时间: 2024-01-07 20:23:35 浏览: 105
以下是使用OpenMP实现归并排序的示例程序:
```c++
#include <iostream>
#include <omp.h>
void merge(double* a, double* b, int start, int mid, int end) {
int i = start, j = mid + 1, k = start;
while (i <= mid && j <= end) {
if (a[i] <= a[j]) {
b[k++] = a[i++];
} else {
b[k++] = a[j++];
}
}
while (i <= mid) {
b[k++] = a[i++];
}
while (j <= end) {
b[k++] = a[j++];
}
for (int i = start; i <= end; i++) {
a[i] = b[i];
}
}
void mergeSort(double* a, double* b, int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
#pragma omp parallel sections
{
#pragma omp section
{
mergeSort(a, b, start, mid);
}
#pragma omp section
{
mergeSort(a, b, mid + 1, end);
}
}
merge(a, b, start, mid, end);
}
}
int main() {
int n = 10; // 数组大小
int p = 4; // 线程数
double* a = new double[n];
double* b = new double[n];
// 初始化数组a和b
#pragma omp parallel for
for (int i = 0; i < n; i++) {
a[i] = rand() / double(RAND_MAX);
b[i] = 0;
}
// 排序数组a和b
double start_time = omp_get_wtime();
mergeSort(a, b, 0, n - 1);
double end_time = omp_get_wtime();
// 检测归并结果是否正确
bool isSorted = true;
for (int i = 1; i < n; i++) {
if (a[i] < a[i - 1]) {
isSorted = false;
break;
}
}
// 输出排序结果和归并时间
if (isSorted) {
std::cout << "归并排序结果:";
for (int i = 0; i < n; i++) {
std::cout << a[i] << " ";
}
std::cout << std::endl;
} else {
std::cout << "归并排序结果不正确!" << std::endl;
}
std::cout << "归并时间:" << end_time - start_time << "秒" << std::endl;
delete[] a;
delete[] b;
return 0;
}
```
阅读全文