Java中传递给函数时的数组功能

Java中传递给函数时的数组功能,java,arrays,Java,Arrays,当我在Java中将数组作为函数参数传递时,请说: public static void main(String... args){ int[] in=new int[]{57,40...23}; int[] post=new int[]{50,18...0};//arrays abbreviated for expediency treeNode tree=buildTree(in, post); print(tree); } public static treeNod

当我在Java中将数组作为函数参数传递时,请说:

public static void main(String... args){
   int[] in=new int[]{57,40...23};
   int[] post=new int[]{50,18...0};//arrays abbreviated for expediency
   treeNode tree=buildTree(in, post);
   print(tree);
}

public static treeNode buildTree(int[] in, int[] post)
{   
   int root_data= post[(post.length)-1];
   int root_index=search(root_data, in);
   treeNode root=new treeNode(root_data);
   root.setLeft(buildTree(subArray(in, 0, root_index),subArray(post, 0, root_index)));
   root.setRight(buildTree(subArray(in,root_index+1, in.length),     
                  subArray(post,root_index, post.length-1)));
   return root;
}

public static int[] subArray(int[] array, int start, int end)
{
    int[] result=new int[end-start];
    for(int i=0; i<end-start;i++)
    {
        result[i]=array[start+i];
    }
    return result;
}

public static int search(int key, int[] array)
{
  for(int i=0; i<array.length; i++){
      if(array[i]==key)
          return key;
  }
  return array.length;
}
publicstaticvoidmain(字符串…参数){
int[]in=新的int[]{57,40…23};
int[]post=newint[]{50,18…0};//为了方便起见,数组被缩写
treeNode树=构建树(in,post);
打印(树);
}
公共静态树节点构建树(int[]in,int[]post)
{   
int root_data=post[(post.length)-1];
int root_index=搜索(root_数据,in);
treeNode根=新的treeNode(根数据);
setLeft(buildTree(子数组(in,0,root_索引),子数组(post,0,root_索引));
setRight(buildTree)(子数组(in,root_索引+1,in.长度),
子数组(post,root_索引,post.length-1));
返回根;
}
公共静态int[]子数组(int[]数组、int开始、int结束)
{
int[]结果=新int[结束-开始];
对于(
search()
方法中的(int i=0;i),您可能希望返回
i
而不是
key
。由于以后使用
root\u index
变量(通过此函数找到)作为数组索引,因此可能会遇到问题(
arrayIndexOutOfBounds
引发异常)。即使
root\u index
在数组索引的范围内,其值仍然是错误的-准确地说,在您的示例中它是
0
,并且
subArray()
方法返回空数组

您可能想考虑使用标准工具而不是自己的方法:

  • Arrays.sort()
    然后是
    Arrays.binarySearch()
    进行搜索:尽管渐进搜索比简单搜索更糟糕-O(n*lon(n))进行排序加O(log(n))进行二进制搜索与O(n)进行比较在你的例子中——考虑到你可能有小数组,这仍然是合理的,但是你得到了算法的保证正确性
  • Arrays.copyOfRange()
    复制数组范围
另外,我没有看到
treeNode
类的任何定义,但我猜您只是为了简洁起见在发布的代码中省略了它

还有一个关于这种风格的简要说明:在Java中,变量和方法是使用camelCase调用的(因此您可能希望将
root\u index
重命名为
rootIndex
等等),类以大写字母开头(因此
treeNode
最好命名为
treeNode
),这将使您的代码更加直观其他人阅读时可以理解


希望有帮助!

在你的代码中你得到了索引xObjut-Frand错误。排序数组可能是个坏主意,因为我的程序正在构建一个二叉树,给定元素的顺序和后置顺序。我在我的线性搜索中修正了bug,但是数组仍然有长度0。你知道为什么吗?你有3种方法,你通过数组:B。uildTree()、subArray()和search()。在其中哪个数组中传递的数组长度为0?如果添加
System.out.println(arrayPassedIn.length);
(其中arrayPassedIn是传递的数组参数的名称)在该方法的最开始?已解决。当传入的数组大小为0时,需要返回一个基本大小写。OK,这很有意义。恭喜!