I have an assignment to use recursion to obtain the largest element in any given array. I have the following code which will work unless the largest element is the last in the array.
Not sure how to correct this?
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;
}
}
}
Your first condition is the problem:
if (myArray.length == 1)
{
return max;
}
replace it with:
if (myArray.length == 1)
{
return myArray[0] > max ? myArray[0] : max;
}
In case of an array with only one element, you return the previous maximum. If the max is that last element, it will be skipped.
you never evaluate the final element - you simply return max when the size of the array is 1, so you never actually check the final element in the array.
also, a comment - rather than creating copies of the array each time, why don't you simply pass the current index into your function every time you recurse?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With