【问题标题】:Recursively output a new array?递归输出一个新数组?
【发布时间】:2015-06-08 20:37:11
【问题描述】:

奇怪的是,我在整个互联网上都没有找到任何关于此的信息。对于家庭作业,当然..,我必须递归地将一个元素添加到已经排序的数组中的正确位置。问题是 - 由于 java 中的数组具有固定大小,我无法更改当前数组,因此我必须创建一个新数组。如果没有递归,这很容易,但由于显而易见的原因,以下代码不起作用:

static int[] recursivelyInsertElement(int[] array, int index, boolean isAdded, int elem) {

    // Takes a sorted array with index = 0 (because.... recursion), an element
    // we'd like to insert and a boolean (default: false) to prevent us from
    // inserting the element more than once. 

    int[] newArray = new int[array.length + 1];

    if (index >= array.length && isAdded) {
        return newArray;
    }

    if (index >= array.length && !isAdded){
        newArray[index] = elem;
        return newArray;
    }

    if (array[index] > elem && !isAdded) {
        newArray[index] = elem;
        isAdded = true;
    }

    newArray[index] = array[index];
    return recursivelyInsertElement(array, index + 1, isAdded, elem);
}


public static void main(String[] args) {

    int[] array = { 1, 3, 5, 7, 9, 11, 45 };

    int elem = 6;

    int[] newArray = recursivelyInsertElement(array, 0, false, elem);

    for (int index = 0; index < newArray.length; index++) {
        System.out.print(newArray[index] + " ");
    }

}


// Expected output: 1 3 5 6 7 9 11 45 
// Actual output: 0 0 0 0 0 0 0 0 
// The obvious issue here is that a new array is initialized on every step.
// What I'd like to do is avoid this.

所以我想知道 - 我应该如何处理这个问题?创建第二个函数,将新数组中的元素相加?虽然我很确定分配的目标是让我的recursivelyInsertElement() 返回新数组本身。

附:如果您只给我建议和提示,而不是完整的解决方案,我将不胜感激!

【问题讨论】:

  • 您没有将旧数组复制到新数组中,或者在每个递归步骤中将部分构造的新数组向下传递
  • 我怎么不这样做?这里的主要问题不是每次调用函数时都会初始化一个新的空白数组吗?
  • 每次调用递归方法都会创建一个新数组 - 之前的新数组中的所有进度都会丢失
  • 在上面添加注释,说明您的每个方法参数是什么,以及如何调用您的方法以及您获得的结果与您期望获得的结果的示例
  • @AmirAfghani 完成!编辑了我的 OP,包括这里和那里的一些澄清 cmets 和 main 方法。

标签: java arrays recursion insert return


【解决方案1】:

所以有几个指针...

  1. 您只需要分配一个新数组 - 那就是当您 已找到正确的位置并即将插入新的 元素。
  2. 当您创建新数组时,您必须从 旧数组进入新数组,移动元素的索引 比新元素大 1 以为其留出空间。
  3. 插入新元素后,您就大功告成了 将新数组一直返回到堆栈中。
  4. 1 和 3 组合意味着您永远不会将新数组传递给 递归调用:您只需要传入原始数组并返回新数组(直接或作为递归的结果)。
  5. 每个递归调用只会增加索引 - 它保证 在某个时候返回。

如果提示足够多,那么就到此为止……!

所以,你的 main 函数没问题,你的 insert 函数应该是这样的:

  if index >= array.length
    // run out of array so add to end
    create new array and copy existing data
    add new element at end of array
    return new array

  if array[index] > elem
    // found the first element greater than the candidate so insert before it
    create new array and copy existing data
    add new element at index
    return new array

  // not found so call again with the next index
  return recusrivelyInsertElement(array, index + 1, elem)

请注意,根据第 3 点,isAdded 标志已消失。

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 1970-01-01
    • 2011-11-13
    • 2016-06-20
    相关资源
    最近更新 更多