简体   繁体   中英

MergeSort and Merge C++

Having an issue with my MergeSort() and Merge() in my homework for school. Im new to C++ (I've been out of school for two years, they changed my major with new classes. I was learning java....) Long story short, my Merge() and MergeSort() functions aren't working in VS Code when I debug them. I'm having issues with the function working in general. I don't know if I'm passing the parameters correctly.

I've tried to change up the Merge() function by moving it up above MergeSort() .

void Merge(int B[], int &lStart, int &lEnd, int &rStart, int &rEnd) {
    int length;
    int temp[length];
    int theSaved = lStart;
    int i = lStart;

    while (lStart < lEnd && rStart <= rEnd) {
        if (B[lStart] < B[rStart]) {
            temp[i++] = B[lStart++];
        }

        else {
            temp[i++] = B[rStart++];
        }
    }

    while (lStart <= lEnd) {
        temp[i++] = B[lStart++];
    }

    while (rStart <= rEnd) {
        temp[i++] = B[rStart++];
    }

    for (int j = theSaved; j < rEnd; j++) {
        B[j] = temp[j];
    }
}

void MergeSort(int B[], int start, int end) {
    int middle;
    int theMiddle = middle + 1;
    if (start < end) {
        middle = (start + end) / 2;
        MergeSort(B, start, middle);
        MergeSort(B, middle + 1, end);
        Merge(B, start, middle, theMiddle, end);
    }
}

int main() {
    int length = 7;
    int begin = 0;
    int end = (length - 1);
    int B[length] = {10, 50, 90, 60, 5, 20, 40};

    for (int i = 0; i < length; i++) {
        MergeSort(B, begin, end);
        cout << "\n" << B[i];
    }
    return 0;
}

I just wanted some insight into what's going on. I tried to do it logically but it ended up being too confusing. The output should be 5,10,20,40,50,60,90

merge() should not be taking parameters by reference, use int lStart instead of int &lStart. rStart will always be lEnd + 1, so only 3 parameters are needed for merge. The if in merge should be lStart <= lEnd.

Although not a problem, the code would be a bit simpler if the initial call from main is MergeSort(B, 0, length). Then Merge could be called with (B, start, middle, end). The loop in merge() would have... lStart < middle... rStart < end... for the loops and if statements.

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