gpt4 book ai didi

java - 递归 split 数组方法

转载 作者:行者123 更新时间:2023-12-02 05:27:38 25 4
gpt4 key购买 nike

我正在尝试编写一个递归方法,该方法采用整数数组并将交替元素复制到两个单独的数组中,直到没有任何元素可供拆分。

例如:

[0 1 2 3 4 5 6 7 8 9]  
...

[0 2 4 6 8]
[1 3 5 7 9] /
[0 4 8]
[2 6] /
[0 8]
[4] /
[0]
[8] /
[2]
[6] /
[1 5 9]
[3 7] /
[1 9]
[5] /
[1]
[9] /
[3]
[7]

到目前为止,我已经能够拆分初始数组,但我的递归不会终止。有什么建议吗?

这是该方法的代码:

public static void halve(int[] a, int x)
{
for (int i = 0; i < x; i = i + 2)
{
xList[i/2] = i;
yList[i/2] = i + 1;
}

printList(xList);
printList(yList);

if (x-1 > 2)
halve(xList, xList.length-1);
else if (x-1 > 2)
halve(yList, yList.length-1);
}

最佳答案

看起来xListyListint[]。在这种情况下,xList.length-1yList.length-1 始终返回相同的数字,因此参数 x 表示 half code> 总是大于 3 并且你的递归永远不会停止。

更不用说其他问题了,比如:

  1. 您正在使用索引而不是 a 的元素填充 xListyList
  2. 如果 x 为奇数,则 i + 1 超出范围。
  3. ifelse if 的条件相同 - 你肯定是有别的意思。

关于java - 递归 split 数组方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25857738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com