Java 在递归方法中,查找数组中最大值的索引

Java 在递归方法中,查找数组中最大值的索引,java,arrays,recursion,Java,Arrays,Recursion,//正如标题所说,我需要找到int//数组中最大值的索引,所有这些都需要在一个方法中完成这就是我的helper//方法到目前为止的样子 它只返回数组中的最后一个索引。我可以很容易地返回最大值,但我不知道如何返回该值的索引 //这是辅助方法 private int recursiveGetIndexOfLargest( int[] list, int count ) { int index; int[] y = list; int temp = count - 1;

//正如标题所说,我需要找到int//数组中最大值的索引,所有这些都需要在一个方法中完成这就是我的helper//方法到目前为止的样子

它只返回数组中的最后一个索引。我可以很容易地返回最大值,但我不知道如何返回该值的索引

//这是辅助方法

private int recursiveGetIndexOfLargest( int[] list, int count )
{
    int index;  
    int[] y = list;
    int temp = count - 1;
    if( count > 0 )
    {
        index = Math.max( list[list.length - 1], list[temp] );
        for(int x = 0; x < y.length; x++)
        {
            if(y[x] == index)
            {
                return x;
            }
        }
        return recursiveGetIndexOfLargest(list, temp);
    }

    else
    {
        return -1;//empty list
    }        
}
它实际上是一个递归完成的O(n)for循环。 你可以这样开始:

int result = findLargestIndex(array,0,0);
这会起作用,但会改变阵列

void findLargestIndex(int[] array, int currentPos)
{
     if(currentPos == array.size()) return;
     array[0] = (array[currentPos] < array[currenPos + 1] ? currentPos + 1 : currentPos;
     findLargestIndex(int[] array, currentPos + 1);
}
试试这个:

 int recursiveGetIndexOfLargest(int[] list, int count)
 {
   if (count == list.length - 1) return count;

   int index = recursiveGetIndexOfLargest(list, count + 1);
   return list[count] > list[index] ? count : index;
 }

 int[] arr = {1, 5, 2, 3, 0};
 System.out.println(recursiveGetIndexOfLargest(arr, 0));

谢谢你,汤姆

参数计数实际上是数组的大小,所以我将它稍微更改为

private int recursiveGetIndexOfLargest( int[] list, int count )
{
    int index;
    int temp = count - 1;
    if( temp == 0 )
    {
        return temp;
    }

    else
    {
        index = recursiveGetIndexOfLargest(list, temp);
        return list[temp] > list[index] ? temp : index;
    }
}

现在它工作了该死的我浪费了几个小时失败了

我无法将参数更改为任何一种方法问题是什么?它必须是一个数组?因为你实际上需要对数组进行一次完整的遍历才能找到元素,也就是O(n)。我想你不是想返回循环变量,而是想返回y[x]?不,我需要返回出现最大值的索引,所以如果数组是{1,5,2,3,0}我需要返回1我无法更改它必须保留的方法的参数(int[]list,int count)好的,请稍候。你能用一个字段来存储currentLargestIndex吗?或者它是一个算法问题解决问题吗?lol我不能改变数组,因为在这个方法之后,我需要调用另一个递归反转数组顺序的方法,然后让我尝试一种移动窗口的方法。我认为不改变数组是不可能的,因为我必须交换两个元素。这是家庭作业吗?我能得到完整的问题陈述吗?
 findLargestIndex(array,0);
 int recursiveGetIndexOfLargest(int[] list, int count)
 {
   if (count == list.length - 1) return count;

   int index = recursiveGetIndexOfLargest(list, count + 1);
   return list[count] > list[index] ? count : index;
 }

 int[] arr = {1, 5, 2, 3, 0};
 System.out.println(recursiveGetIndexOfLargest(arr, 0));
private int recursiveGetIndexOfLargest( int[] list, int count )
{
    int index;
    int temp = count - 1;
    if( temp == 0 )
    {
        return temp;
    }

    else
    {
        index = recursiveGetIndexOfLargest(list, temp);
        return list[temp] > list[index] ? temp : index;
    }
}