1

嗨,我仍然不知道为什么我的代码让我的堆栈溢出它的接缝,我的合并排序算法的下限和上限改变了不应该做的地方..

    int[] arr = new int[10];
    private void button1_Click(object sender, EventArgs e)
    {
        merge_sort(0, 9);
    }

    private void merge_sort(int left, int right)
    {
        if (left > right)
            merge(left, right, (left + right) / 2);
        else
            merge_sort((left + right) / 2 + 1, right);
        merge_sort(left, (left + right) / 2);

    }
    void merge(int low, int high, int mid)
    {
        int i, j, k, t;
        j = low;
        for (i = mid + 1; i <= high; i++)
        {
            while (arr[j] <= arr[i] && j < i)
                j++;
            if (j == i)
                break;
            t = arr[i];
            for (k = i; k > j; k--)
                arr[k] = arr[k - 1];
            arr[j] = t;
        }
    }
4

3 回答 3

1

您的 merge_sort 递归方法将永远不会结束,因为总是调用最后一行再次调用 merge_sort ......它是无限递归的,这应该会导致 stackoverflow。

private void merge_sort(int left, int right)
{
    if (left > right)
    merge(left, right, (left + right) / 2);
 else
    merge_sort((left + right) / 2 + 1, right);
 merge_sort(left, (left + right) / 2);  //<-- this is your problem!
} 

我认为(也许)你想这样做:

private void merge_sort(int left, int right)
{
    if (left > right)
    merge(left, right, (left + right) / 2);
 else
 {
    merge_sort((left + right) / 2 + 1, right);
    merge_sort(left, (left + right) / 2)
 }
} 
于 2012-05-17T11:13:18.507 回答
0

你有

merge_sort((left + right) / 2 + 1, right);

我认为应该是

merge((left + right) / 2 + 1, right);
于 2012-05-17T11:10:02.177 回答
0

我已经像这样更改了我的代码。堆栈溢出问题已解决,但我没有得到正确的结果!!!

    private void merge_sort(int left, int right)
    {
        if (left > right)
            merge(left, right, (left + right) / 2);
        else
        {
            merge_sort((left + right) / 2 + 1, right);
            merge(left, right, (left + right) / 2+1);

        }

    }

最近我发现如何通过更改我的部分代码来控制它,但我仍然不明白是什么问题!!!!这是更改:

    private void merge_sort(int low, int high)
    {

int mid;
        if (low != high)
        {
            mid = (low + high) / 2;
            merge_sort(low, mid);
            merge_sort(mid + 1, high);
            merge(low, mid, high);
        } 
于 2012-05-17T19:43:07.673 回答