【问题标题】:Mergesort code not working [duplicate]合并排序代码不起作用[重复]
【发布时间】:2014-03-17 18:19:15
【问题描述】:

我正在使用C#来实现mergesort()的代码; 这是我在 main() 中编写的代码

static void Main(string[] args)
    {
        int[] arr = { 5,9,2,-10,53,-64,10,22,15,-60,2,3};
        Merge(arr,0,6,12);
    }

这里是 Merge() 函数

public static void Merge(int[] arr,int p,int q,int r ) 
    {
        int n1 = q-p;
        int n2 = r-q;
        int[] L=new int[n1];
        int[] R = new int[r-n2];
        for (int i = 0; i < n1; i++)
            L[i] = arr[i];
        foreach (int x in L)
            Console.WriteLine(x);
        for (int i = 0; i < r-n2; i++)
            R[i] = arr[q+i];
        Console.WriteLine("New part");
        foreach (int x in R)
            Console.WriteLine(x);
        int k=0, d=0;
        for (int i = p; i < r; i++)
        {
            if (L[k] <= R[k])
            {
                arr[i] = L[k];
                k++;
            }
            else
            {
                arr[i] = R[d];
                d++;
            }
        }
    }

代码显示异常为索引超出范围,引用包含 int n1 = q-p; 的行号和合并(arr,0,6,12); 谁能帮帮我

【问题讨论】:

  • 不要两次发布相同的问题。如果您编辑代码,请在原始问题中进行。
  • 我不相信那是引发异常的那一行。
  • 问两个包含几乎相同代码/抛出相同异常的代码的问题通常表明您在使用Stack Overflow 方面做错了。您绝对不应该随时更新问题中的代码(因为这破坏了Stack Overflow 模型),而是尝试在询问之前调试您的程序,如果您最终仍然没有完全弄清楚它出来,试着用这样的方式来表达这个问题,答案会告诉你从那里弄清楚你需要知道的一切。

标签: c# algorithm sorting


【解决方案1】:

R[] 的长度 = r - n2 = 12 - (12 - 6) = 6。

在最后一个 for 循环中,您在 i

for (int i = p; i < r; i++)
    {
        if (L[k] <= R[k])
        {
            arr[i] = L[k];
            k++;
        }
        else
        {
            arr[i] = R[d];
            d++;
        }
    }

异常从 arr[i] = R[d] 触发。

编辑:你确定你对 R[] 长度的定义吗?

int n2 = r - q;
...
int[] R = new int[r-n2]; // this is the same as int[] R = new int[q].

【讨论】:

    猜你喜欢
    • 2014-04-22
    • 1970-01-01
    • 2016-02-06
    • 2016-08-19
    • 1970-01-01
    • 2018-12-04
    • 2015-02-09
    • 1970-01-01
    相关资源
    最近更新 更多