Your recursive logic is fine: to reverse an array, we reverse the first and last element and do that again on the array without those elements. That means we need to swap the first and the last element together and call the method again, incrementing the first index and decrementing the last index. In your code, however, you are only changing tempArray[startIndex] and not tempArray[endIndex].
The base condition is wrong though: there is nothing to do, not when the first element is equal to the last element, but when the first index is greater or equal than the last index (if it is equal, there is only one element to consider and so the reverse is also the same element).
Putting this into code, this turns into:
private static int[] reverseArray(int[] array, int startIndex, int endIndex) {
if (startIndex >= endIndex) { // base condition, nothing to do when there is one or no element to consider
return array;
}
// swap array[startIndex] and array[endIndex]
int temp = array[startIndex];
array[startIndex] = array[endIndex];
array[endIndex] = temp;
// recurse with the decreasing bounds
return reverseArray(array, startIndex + 1, endIndex - 1);
}
Note that I removed the declaration of the tempArray: we can consider directly array. Then, we can add a utility method:
public static int[] reverseArray(int[] array){
return reverseArray(array.clone(), 0, array.length - 1);
}
Note that I made this method public and the other one private: the one you will want to call will be this one since it hides the recursive implementation. I added a call to clone() in there so as not to modify the given array when calculating the reverse.
array[startIndex]andarray[endIndex]to reverse the array overall. Also, think about the stopping condition - why does the equality of element values matter?tempArrayis simply an alias forarray- you aren't making a copy of the array by doing that. It only serves to make the code more complicated.