分段错误对字符串进行合并排序

时间:2018-10-08 19:10:40

标签: c++ arrays string sorting mergesort

现在已经调试了一段时间,而我似乎找不到的问题(可能只是缺少一些愚蠢的问题)是我的归类排序功能(在int数组上工作)不能在数组上工作字符串。

void MergeSort(string *input, int lowBound, int highBound)
{
    int midBound;
    if (lowBound < highBound)
    {
        midBound = (lowBound + highBound) / 2;

        MergeSort(input, lowBound, midBound);
        MergeSort(input, midBound + 1, highBound);

        MergeArrs(input, lowBound, highBound, midBound);
    }
}

void MergeArrs(string *a, int lowBound, int highBound, int midBound)
{
    int i, j, idx; 
    string tmp[highBound - lowBound + 1];
    i = lowBound; //Index for front arr
    idx = 0;
    j = midBound + 1; //Index for back arr

    while (i <= midBound && j <= highBound)
    {
        if (a[i] < a[j])
        {
            tmp[idx] = a[i];
            idx++;
            i++;
        }
        else
        {
            tmp[idx] = a[j];
            idx++;
            j++;
        }
    }

    while (i <= midBound)
    {
        tmp[idx] = a[i];
        idx++;
        i++;
    }

    while (j <= highBound)
    {
        tmp[idx] = a[j];
        idx++;
        j++;
    }

    for (i = lowBound; i <= highBound; i++)
    {
        a[i] = tmp[i - lowBound];
    }
}

如果任何人都知道段错误来自何处,将不胜感激。我的测试数组如下:

string arr[6] = {"alpha", "beta", "omega", "zeta", "epsilon", "beach"};

并且这样称呼:

MergeSort(arr, 0, 6);

1 个答案:

答案 0 :(得分:0)

我不是一个聪明人。通过索引,在我的归类排序调用中,超过0到5的程序可以工作,因为,嗯,这是最高和最低的索引。

它不会与int进行段错误,因为它是@phlipsy所说的原始数组。