I have a purpose to use recursion to get the largest element in any given array. I have the following code that will work if the largest element is not the last in the array.
Not sure how to fix 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; } } }
source share