For something I am working on I need to have an integer array, and get two indices from the user. One being a starting point in the array, and the other being an ending point. With these two points I have to find the max value within the array, recursively. The code I currently have works, but I feel like there are things that could make it more fluent, and maybe even I could do somethings different to get rid of some useless code. I will post my code below.
import java.util.Scanner;
public class RecursiveProblem {
public static void main(String args[]) {
int start, end, size, max;
Scanner scan = new Scanner(System.in);
System.out.println("How many numbers would you like to enter in total?");
size = scan.nextInt();
int[] myArray = new int[size];
System.out.println("Please enter the specified starting index.");
start = scan.nextInt() - 1;
System.out.println("Please enter the specified ending index.");
end = scan.nextInt() - 1;
System.out.println("Please enter " + size + " integers seperated by a space, or press "
+ "enter after each number: ");
for(int i = 0; i < myArray.length; i++) {
myArray[i] = scan.nextInt();
}
scan.close();
max = myArray[start];
max = findMax(myArray, start, end, max);
System.out.println("The max of your array between the indices of " + (start + 1) +
"-" + (end + 1) + " is..." + max);
}
public static int findMax(int[] myArray, int start, int end, int max) {
if(start < end) {
if(myArray[start + 1] > max) {
start++;
max = myArray[start];
return findMax(myArray, start, end, max);
}
else {
start++;
return findMax(myArray, start, end, max);
}
}
return max;
}
}
One thing I am mainly confused about, but not the only question I have--is whenever I opt to put the start++ command inside the function call for findMax(myArray, start++, end, max) <--(like so), it will end up in infinite recursion. I am confused as to why this causes infinite recursion, but the way I did it does not. Thank you in advance for the assistance on cleaning up the code, and helping me out with my question!
++startinstead ofstart++would make sure thestartvariable is increased by one before invoking the method and thereby avoiding the infinite loop.