【发布时间】: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