简体   繁体   English

为什么此合并排序中存在分段错误?

[英]Why is there segmentation fault in this merge sort?

I compiled this code on different compilers, but all of them gave runtime error.我在不同的编译器上编译了这段代码,但它们都给出了运行时错误。 Can someone tell me what's wrong with this code?有人能告诉我这段代码有什么问题吗?

void merge(int *str, int beg, int mid, int end) {
    int *arr = new int[end - beg + 1];
    int k = 0;
    int i = beg;
    int j = mid + 1;
    while (i <= mid && j <= end) {
        if (str[i] < str[j]) {
            arr[k] = str[i];
            i++;
            k++;
        } else {
            arr[k] = str[j];
            j++;
            k++;
        }
    }
    while (i <= mid) {
        arr[k] = str[i];
        i++;
        k++;
    }
    while (j <= end) {
        arr[k] = str[j];
        //here i got buffer overrun while writing to arr
        j++;
        k++;
    }
    for (i = beg; i <= end; i++) {
        str[i] = arr[i - beg];
    }
    delete[] arr;
}

void merge_sort(int *str, int beg, int end) {
    
    if (beg >= end)
        return;

    int mid = (end - beg) / 2;
    merge_sort(str, beg, mid);
    merge_sort(str, mid + 1, end);
    merge(str, beg, mid, end);
}

This code is almost same as I found on Sanfoundry, but that one is working but mine got some errors.这段代码与我在 Sanfoundry 上找到的代码几乎相同,但该代码正在运行,但我的代码出现了一些错误。

Your computation of the mid point in merge_sort is incorrect: instead of int mid = (end - beg) / 2;您对merge_sort中点的计算不正确:而不是int mid = (end - beg) / 2; you should write:你应该写:

    int mid = beg + (end - beg) / 2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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