【问题标题】:Send Array back to main method将数组发送回主方法
【发布时间】:2016-12-07 03:55:27
【问题描述】:
public static void main(String[] args) {
    Integer[] ar = new Integer[] { 5, 2, 1, 12, 2, 10, 4, 13, 5 };
    processD(ar);

    System.out.println("Sorted: " + Arrays.toString(ar));
}

我基本上是在尝试将Integer[] 移动到processD 方法,然后通过main 方法打印回输出。我真的不知道我做错了什么。我知道大多数程序都可以正常工作,因为如果我将打印命令放在processD 函数中,它就可以完美运行。但在 main 方法中,它只是打印输入而不处理它。任何帮助将不胜感激。谢谢

public class MethodBeta {

  public static void processD(Integer[] iA) {

    int[] array = new int[iA.length];
    for (int u = 0; u < iA.length; u++) {
      array[u] = iA[u].intValue();
    }
    // If array is smaller than 2 then already sorted
    if (array.length < 2) {
      return;
    }

    // create sub-arrays and keep multiplying by 2 to increase their number
    int z1 = 1;
    int z2, z3;

    while (z1 < array.length) {
      z2 = 0;
      z3 = z1;

      while (z3 + z1 <= array.length) {

        merge(array, z2, z2 + z1, z3, z3 + z1);
        z2 = z3 + z1;
        z3 = z2 + z1;
      }
      if (z3 < array.length) {
        merge(array, z2, z2 + z1, z3, array.length);
      }
      z1 *= 2;
    }
  }

  public static void merge(int[] ar1, int startL, int stopL, int startR, int stopR) {

    int[] right = new int[stopR - startR + 1];
    int[] left = new int[stopL - startL + 1];

    for (int i = 0, k = startR; i < (right.length - 1); ++i, ++k) {
      right[i] = ar1[k];
    }
    for (int i = 0, k = startL; i < (left.length - 1); ++i, ++k) {
      left[i] = ar1[k];
    }

    right[right.length - 1] = Integer.MAX_VALUE;
    left[left.length - 1] = Integer.MAX_VALUE;

    for (int z = startL, x = 0, y = 0; z < stopR; ++z) {
      if (left[x] <= right[y]) {
        ar1[z] = left[x];
        x++;
      } else {
        ar1[z] = right[y];
        y++;
      }
    }

  }

  public static void main(String[] args) {
    Integer[] ar = new Integer[] { 10, 9, 8, 7, 2, 10, 4, 13, 5 };
    processD(ar);
    System.out.println("Sorted: " + Arrays.toString(ar));
  }

}

【问题讨论】:

  • 你在processD(ar);做什么?可以展示一下吗?
  • 我需要在 main 方法中添加打印功能。那么实现这一点的最佳方法是什么?而processD基本上就是一个通过数组的排序过程……
  • @AndrewLi 对象的值是它的引用。 Integer[] 的工作方式相同,所以我相信实际的数组会改变?
  • 我认为这里可能存在问题: public static void mergeSortB(Integer[] inputArray){ int[] array = new int[inputArray.length]; for (int m = 0; m

标签: java methods process


【解决方案1】:

您的 public static void processD(Integer[] iA) - 复制本地 array 变量中的值,在该本地变量上完成所有工作,但从不复制回 iA 参数中的值

当然iA 参数保持不变。

完成后,在方法结束时,只需:

for(int i=0; i<array.length; i++) {
  iA[i]=array[i];
}

【讨论】:

  • 您能告诉我如何解决它吗?就像将本地数组移回 main 方法一样?或将值复制回 iA?谢谢你..
  • @YuanGuo 那里。
  • 感谢您的帮助!只有一个问题;这将被视为就地排序吗?我的意思是这个问题
  • @YuanGuo "这会算作就地排序吗?"没有。因为合并方法中的前两行是int[] right = new int[stopR - startR + 1]; int[] left = new int[stopL - startL + 1]; - 那些new int 突然使该方法“带有额外的空间”
猜你喜欢
  • 2013-10-29
  • 2013-07-16
  • 1970-01-01
  • 2014-03-30
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
  • 2018-03-21
  • 1970-01-01
相关资源
最近更新 更多