我已经编写了并行实现的合并排序,但由于某些原因,我无法理解,有时它会正确完成,有时它会崩溃。更有趣的下面的代码有时似乎崩溃后它已经排序数组(数组被打印,然后代码停止工作)。
有人可以帮我诊断问题吗?我想我用线程弄乱了一些东西并且它们没有正确结束?
void printArray (int* a, int elements) {
for(int i = 0; i < elements; i++) {
printf("%d\t", a[i]);
}
}
void merge2(int a[], int l, int middle, int r) {
int leftIterator = l;
int rightIterator = middle+1;
int k = 0;
int* tmp = new int[(r - l)];
while (leftIterator <= middle && rightIterator <= r) {
if (a[leftIterator] < a[rightIterator]) {
tmp[k] = a[leftIterator];
leftIterator++;
}
else {
tmp[k] = a[rightIterator];
rightIterator++;
}
k++;
}
if (leftIterator <= middle) {
while (leftIterator <= middle) {
tmp[k] = a[leftIterator];
leftIterator++;
k++;
}
}
else {
while (rightIterator <= r) {
tmp[k] = a[rightIterator];
rightIterator++;
k++;
}
}
for (int i = 0; i <= (r - l); i++)
a[l + i] = tmp[i];
}
void merge_sort(int a[], int l, int r) {
if (l != r) {
int middle= (l + r) / 2; //find middle element
#pragma omp parallel sections
{
#pragma omp section
merge_sort(a, l, middle);
#pragma omp section
merge_sort(a, middle + 1, r);
}
merge2(a, l, middle, r);
}
}
int main(void) {
int elements = 10;
int a[10] = { 10,2,1,5,6,3,4,9,8,7 };
merge_sort(a, 0, elements-1);
printArray(a, elements); // print sorted array
printf("\n");
return 0;
}