c++ - 为什么我的合并排序不起作用?

标签 c++ sorting

它编译得很好,但是当它运行时,它会向列表中添加随机的高数字以及现有数字的重复项。我让几个人研究过这个问题,但没有一个人能弄清楚。

void mergeSort(int list[], int length) {
    recMergeSort(list, 0, length - 1);
}

void recMergeSort(int list[], int first, int last) {

    if (first < last) {
        int mid = (first + last) / 2;
        recMergeSort(list, first, mid);
        recMergeSort(list, mid + 1, last);
        merge(list, first, last, mid);
    }
}

void merge(int list[], int first, int last, int mid) {

    int arraySize = last - first + 1;
    int* tempList = new int[arraySize];
    int beginPart1 = first;
    int endPart1 = mid;
    int beginPart2 = mid + 1;
    int endPart2 = last;


    int index = beginPart1;


    while (beginPart1 <= endPart1 && beginPart2 <= endPart2) {
        if (list[beginPart1] < list[beginPart2]) {
            tempList[index] = list[beginPart1];
            beginPart1++;
        }
        else {
            tempList[index] = list[beginPart2];
            beginPart2++;
        }
        index++;
    }

    while (beginPart1 <= endPart1) {
        tempList[index] = list[beginPart1];
        index++;
        beginPart1++;
    }

    while (beginPart2 <= endPart2) {
        tempList[index] = list[beginPart2];
        index++;
        beginPart2++;
    }


    for (int i = first; i <= last; i++) {
        list[i] = tempList[i - first];
    }

    delete[] tempList;
}

最佳答案

在函数 merge() 中,您错误地计算了 index 变量:

假设 begin = 10、mid = 14、end = 19(数组总大小为 0 .. 19,并且您正在 recMergeSort()ing 上半部分),您的索引 = 10,但 tempList 数组的索引为 0..9(因为 arraySize = last - first + 1 = = 10)。

因此,您的 tempList 数组溢出,当您“合并”时,数据会损坏。

将您的 index 变量修复为从 0 开始(而不是基于 beginPart1)。

关于c++ - 为什么我的合并排序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1663119/

相关文章:

c++ - 为 vector 重载 "+,-,*"运算符时出现问题 - "no match for operator..."

c++ - 如何使用 uint8_t 而不是 char?

c++ - 如何在没有内存泄漏的情况下登录 ISA Server 2006 C++ SDK

objective-c - 如何对 NSStrings 的 NSTableColumn 进行排序而忽略 "The "和 "A "?

python - 排序 XML 文件

c++ - 函数采用可变数量的不同类型的 initializer_lists

c++ - CUDA TCC 驱动程序是否适用于 Windows 上的 geforce 卡?

java - 排序/比较不同的标准

algorithm - 这3个类轮是什么排序算法?

python - 在 Python 中按日期时间对缺少日期的用户列表进行排序