简体   繁体   中英

mergesort c++ implementation out of bound index accessing

I'm implementing the merge sort psuedocode from the CLRS algorithms textbook in c++. Somewhere in my code I access an element of an array that's not in the bounds of the array. I'm not sure why this happens (it occurs when the left == size of array -1, middle == left, right == size of array). I'd really appreciate any help. Here is my implementation.

void merge(int array[], int left, int middle, int right) {
    int left_size = middle - left + 1; //include middle
    int right_size = right - middle;

    int *left_array = new int[left_size];
    int *right_array = new int[right_size];

    for (int i = 0; i < left_size; i++)
        left_array[i] = array[left + i];
    for (int i = 0; i < right_size; i++)
        right_array[i] = array[middle + i + 1];

    int i = 0;
    int j = 0;
    int cur = left;

    printArray(left_array, left_size);
    printArray(right_array,right_size);

    while (i < left_size and j < right_size) {
        if (left_array[i] < right_array[j])
            array[cur] = left_array[i++];
        else
            array[cur] = right_array[j++];
        cur++;
    }

    while (i < left_size) {
        array[cur] = left_array[i++];
        cur++;
    }
    while (j < right_size) {
        array[cur] = right_array[j++];
        cur++;
    }

    delete [] left_array;
    delete [] right_array;
}

This is how i call the merge function:

void mergeSort(int array[], int length) {
    mergeSortHelper(array, 0, length);
}


//left inclusive, right exclusive
void mergeSortHelper(int array[], int left, int right) {
    if (left < right) {
        int middle = floor((left + right) / 2);
        mergeSortHelper(array, left, middle);
        mergeSortHelper(array, middle + 1, right);
        merge(array, left, middle, right);

    }
}

When you start with:

mergeSortHelper(array, 0, length);

you will cause array[length] to be used. array [length-1] is the last valid refererence.

It might work better if you start with:

mergeSortHelper(array, 0, length-1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM