使用递归获取数组中的最大元素

NYC*_*uck 4 java arrays recursion

我有一个使用递归来获取任何给定数组中最大元素的赋值.我有以下代码,除非最大的元素是数组中的最后一个,否则它将起作用.

不知道如何纠正这个?

import java.util.Scanner;
public class RecursionLargestInArray
{
public static void main (String[] args)
{
    int max = -999;
    Scanner scan = new Scanner (System.in);
    System.out.print("Enter the size of the array: ");
    int arraySize = scan.nextInt();
    int[] myArray = new int[arraySize];
    System.out.print("Enter the " + arraySize + " values of the array: ");
    for (int i = 0; i < myArray.length; i++)
        myArray[i] = scan.nextInt();
    for (int i = 0; i < myArray.length; i++)
        System.out.println(myArray[i]);
    System.out.println("In the array entered, the larget value is "
                        + getLargest(myArray, max) + ".");
}

public static int getLargest(int[] myArray, int max)
{    
    int i = 0, j = 0, tempmax = 0;
    if (myArray.length == 1)
    {
        return max;
    }
    else if (max < myArray[i])
    {
        max = myArray[i];
        int[] tempArray = new int[myArray.length-1];
        for (i = 1; i < myArray.length; i++)
        {
            tempArray[j] = myArray[i];
            j++;
        }
        tempmax = getLargest(tempArray, max);
        return tempmax;
    }
    else if
    {
        int[] tempArray = new int[myArray.length-1];
        for (i = 1; i < myArray.length; i++)
        {
            tempArray[j] = myArray[i];
            j++;
        }
        tempmax = getLargest(tempArray, max);
        return tempmax;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 6

你的第一个条件是问题:

if (myArray.length == 1)
{
    return max;
}
Run Code Online (Sandbox Code Playgroud)

替换为:

if (myArray.length == 1)
{
    return myArray[0] > max ? myArray[0] : max;
}
Run Code Online (Sandbox Code Playgroud)

如果数组只包含一个元素,则返回先前的最大值.如果max是最后一个元素,则将跳过它.