سؤال

I am learning how to implement mergesort in c++ and encountered the following problem.

This is my merge function that merges two sorted arrays into one sorted array.

void merge(int *list, int *final, int start, int mid, int stop) {
    int h = start;
    int i = start;
    int j = mid + 1;

    while ((h <= mid) && (j <= stop)) {
        if (list[h] <= list[j]) {
            final[i] = list[h];
            h++;
        } else {
            final[i] = list[j];
            j++;
        }
        i++;
    }

    /* CODE A */
    if (h > mid) {
        for (int k = j; k <= stop; k++) {
            final[i] = list[k];
            i++;
        }
    } else {
        for (int k = h; k <= mid; k++) {
            final[i] = list[k];
            i++;
        }
    }
    /* End of CODE A */

    /* CODE B */
    while ( h <= mid) {
        list[i] = final[h];
        i++; h++;
    }

    while ( j <= stop ) {
        list[i] = final[j];
        i++; j++;
    }
    /* End of CODE B */

    for (int k = start; k <= stop; k++) {
        list[k] = final[k];
        printArray(list, 4, "Intermediate Array: ");
    }
}

At any one time, I use either CODE A or CODE B. When I use CODE A, the function executes as intended. However, when I use CODE B, the function fills the array, list, with random data.

printArray is a custom function to print the array, list. When sorting a set of numbers, {4, 2, 6, 9}, I get this output from the printArray function:

Intermediate Array: 2 2 6 9 <br>
Intermediate Array: 2 -790123182 6 9<br>
Intermediate Array: 2 -790123182 6 1968115546<br>
Intermediate Array: 2 -790123182 6 1968115546<br>
Intermediate Array: 2 -790123182 6 1968115546<br>
Intermediate Array: 2 -790123182 6 1968115546<br>
Intermediate Array: 2 -790123182 6 1968115546<br>
Intermediate Array: 2 -790123182 6 1968115546<br>
هل كانت مفيدة؟

المحلول

In code B the assignment from list to final is in the wrong direction. Try this instead:

/* CODE B */
while ( h <= mid) {
    final[i] = list[h];
    i++; h++;
}

while ( j <= stop ) {
    final[i] = list[j];
    i++; j++;
}
/* End of CODE B */
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top