【问题标题】:Arraycopy Crashing My ProgramArraycopy 使我的程序崩溃
【发布时间】:2012-02-12 21:55:54
【问题描述】:

我正在做一项家庭作业,我必须根据我们书籍的作者伪代码来实现 MergeSort。 (算法基础,那不勒斯和 Naimipour 的第 4 版)。

从主要方法中,我调用了 mergeSort,其中 int n 是数组的长度,S[] 是需要排序的数组。 S[] 已经填充了 1 到 999 之间的随机数。我的程序在合并的最后一个 arraycopy 处崩溃,我不确定为什么会这样,我已经尝试在 netbeans 中进行调试。我觉得这可能是一个我看不到的愚蠢错误。任何帮助都会很棒。提前致谢。

public static void mergesort (int n, int S[])
   {
      if(n>1){
         final int h=n/2, m=n-h;
         int U[] = new int[h];
         int V[] = new int[m];
         System.arraycopy(S, 0, U, 0, h);
         System.arraycopy(S, h, V, 0, m);
         mergesort(h, U);
         mergesort(m, V);
         merge(h, m, U, V, S);
      }
   }
   public static void merge(int h, int m, final int U[], final int V[], final int S[])
   {
      int i=0, j=0, k=0;
      while(i<h && j<m){
         if(U[i]<V[j]) {
            S[k] = U[i];
            i++;
         }
         else {
            S[k]=V[j];
            j++;
         }
         k++;
      }
      if(i>h)
         System.arraycopy(V, j, S, k, h+m);
      else
         System.arraycopy(U, i, S, k, h+m);
   }

编辑:我意识到我在合并中有几个小错误。最大的变化是更改比较以使用 equals,并且了解 arraycopy 中的长度是我想要复制的元素的数量。这是我的合并方法。合并排序保持不变。

   public static void merge(int h, int m, final int U[], final int V[], int S[])
   {
      int i=0, j=0, k=0;
      while(i<h && j<m){
         if(U[i]<V[j]) {
            S[k] = U[i];
            i++;
         }
         else {
            S[k]=V[j];
            j++;
         }
         k++;
      }
      if(i>=h)
         System.arraycopy(V, j, S, k, m-j);
      else
         System.arraycopy(U, i, S, k, h-i);
   }

感谢您的帮助。

【问题讨论】:

  • 发布堆栈跟踪(Exception.printStacktrace())。可能是堆栈溢出、内存不足或索引超出范围...
  • 另外,用作业标记它,这样我们就不会给出完整的解决方案:)。祝你好运!

标签: java recursion mergesort arrays


【解决方案1】:

测试过了。它作为一个 IndexOutOfBounds。 原因是您在 ArrayCopy 中给出的长度大于源数组的计数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 2011-05-26
    • 2013-08-20
    • 2021-08-28
    相关资源
    最近更新 更多