从索引a到索引b的迭代合并

时间:2016-11-05 19:32:05

标签: c++ arrays sorting valgrind mergesort

我试图让某种类型的mergesort进入mergesort(int[] a, int start, int stop),其中start是开始排序的索引,stop是停止排序的索引。我的想法是,我可以有4个不同的线程同时排序数组的4个子部分。所以我可以在不同的线程上调用类似mergesort(a, 0, length/4); mergesort(a, length/4, length/2); mergesort(a, length/2, (3/4)*length); etc.的东西。

我遇到过从0length的一堆迭代算法,但是当我编辑这些算法时,试图让它们与数组的子部分一起工作在Valgrind中查看输入过大的段错误和一堆无声错误。

这就是我现在所拥有的:

void mergesort(int *a, int *b, int low, int high) {
    int pivot;
    if (low < high) {
        pivot = (low + high)/2;
        if(level < maxlevel) { // If we have not reached the max threads to spawn
            mergesort(a, b, low, pivot); // Need to change these to spawn threads
            mergesort(a, b, pivot + 1, high);
            merge(a, b, low, pivot, high);
        } else {
            level += 2; // To tell when we can stop spawning threads
            for (int curr_size=1; curr_size<=(high-low)-1; curr_size = 2*curr_size) {
                // Pick starting point of different subarrays of current size
                for (int left_start=low; left_start<high; left_start += 2*curr_size) {
                    // Find ending point of left subarray. mid+1 is starting 
                    // point of right
                    int mid = left_start + curr_size - 1;
                    int right_end = min(left_start + 2*curr_size - 1, high);
                    // Merge Subarrays arr[left_start...mid] & arr[mid+1...right_end]
                    merge(a, b, left_start, mid, right_end);
                }
            }
        }
    }
}

输出是一个排序数组,如果它没有段错误。但是对于valgrind,总会有一个这样的实例&#34;无效的写入大小为4&#34;错误:https://puu.sh/s7zb2.png

这是我使用的合并功能:

void merge(int *a, int *b, int low, int pivot, int high)
{
    cout << "merging " << low << " to " << high << endl;
    int h, i, j, k;
    h = low;
    i = low;
    j = pivot + 1;

    while ((h <= pivot) && (j <= high)) {
        if (a[h] <= a[j]) {
            b[i] = a[h]; // store element of left half in the temporary array
            h++; // shift the index of the array from which the element was copied to temporary 
        }
        else {
            b[i] = a[j];
            j++; // shift the index of the array from which the element was copied to temporary 
        }
        i++;
    }
    if (h > pivot) {
        for (k = j; k <= high; k++) {
            b[i] = a[k];
            i++;
        }
    } else {
        for (k = h; k <= pivot; k++) {
            b[i] = a[k];
            i++;
        }
    }
    for (k = low; k <= high; k++) a[k] = b[k]; // recopy the values from temporary to original array.
}

出了什么问题?我感觉合并功能的原因是试图访问它不应该的值,但我似乎无法找到发生这种情况的地方。

由于

0 个答案:

没有答案