patternjavaMinor
Getting the largest element in an array using recursion
Viewed 0 times
therecursionarraygettinglargestelementusing
Problem
Any suggestions on how to make this code more efficient?
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 max ? myArray[0] : 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
{
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;
}
}
}Solution
I would use a helper function, and I would avoid copying the array (using indices instead):
Using varargs
In case you really want to copy the array, use
public static int getLargest(int ... myArray) {
return getLargest(myArray, 0, myArray.length);
}
private static int getLargest(int[] myArray, int from, int to) {
if(from == to) {
throw new IllegalArgumentException("empty array");
} else if (from + 1 == to) {
return myArray[from];
} else {
int middle = (from + to) / 2;
return Math.max(getLargest(myArray, from, middle),
getLargest(myArray, middle, to));
}
}Using varargs
int ... instead of an array int[] for the argument makes it more flexible, e.g. better testable.In case you really want to copy the array, use
System.arraycopy, which is much faster than looping through.Code Snippets
public static int getLargest(int ... myArray) {
return getLargest(myArray, 0, myArray.length);
}
private static int getLargest(int[] myArray, int from, int to) {
if(from == to) {
throw new IllegalArgumentException("empty array");
} else if (from + 1 == to) {
return myArray[from];
} else {
int middle = (from + to) / 2;
return Math.max(getLargest(myArray, from, middle),
getLargest(myArray, middle, to));
}
}Context
StackExchange Code Review Q#6057, answer score: 6
Revisions (0)
No revisions yet.