简体   繁体   中英

How to reverse an integer array using recursion in java?

I'm trying to reverse an integer array using a recursive method. I'm really bad with recursion so far, and I was wondering if someone could help me with this problem that I'm having.

Here is my code so far:

public static int[] reverseArray(int[] array, int startIndex, int endIndex){
    int[] tempArray = array;
    if(tempArray[startIndex] == array[endIndex]){
        return tempArray;
    }
    else{
        tempArray[startIndex] = array[endIndex];
        reverseArray(array, startIndex + 1, endIndex - 1);
        return tempArray;
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM