奇怪的是,我没有在整个互联网上找到关于此的任何信息。对于家庭作业,当然..,我必须递归地将一个元素添加到已经排序的数组中的合法位置。问题是 - 由于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()
返回新的数组本身。
P.S。如果你给我的建议和提示,而不是整个解决方案,我将不胜感激!
答案 0 :(得分:1)
所以一些指示......
如果这是足够的提示,请停在这里......!
所以,你的主要功能很好,你的插入功能应该是这样的:
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
标志已经消失。
希望这有帮助