4
\$\begingroup\$

We have to reverse char[] using recursion.

  • Input: ["H","a","n","n","a","h"]
  • Output: ["h","a","n","n","a","H"]
package codeMonk;

public class RevereseString {

    public  char[] reverseStr(char[] reversedString, int startIndex , int lastIndex, int midIndex) {

        // Base Condition
        if(startIndex > midIndex || midIndex >= lastIndex){
            return reversedString;
        } else {
            char storeChar = reversedString[startIndex];
            reversedString[startIndex] = reversedString[lastIndex -1];
            reversedString[lastIndex -1 ] = storeChar;
            return reverseStr(reversedString, ++startIndex , --lastIndex, midIndex);
        }
    }

    public static void main(String[] args) {
        char[] oldArray = {'A',' ','m','a','n',',',' ','a',' ','p','l','a','n',',',' ','a',' ','c','a','n','a','l',':',' ','P','a','n','a','m','a'};
        int midIndex = 0 + (oldArray.length - 0)/2 ;
        RevereseString reverseStr = new RevereseString();
        char [] newArray = reverseStr.reverseStr(oldArray, 0 , oldArray.length, midIndex);
        for(char ch : newArray) {
            System.out.print(ch +" ");
        }
    }

}

This code works fine, but how can I improve it and reduce the lines of code?

\$\endgroup\$
4
\$\begingroup\$

You are not using any stored data in the RevereseString [sic] object, so you do not actually need to create the object. Changing reverseStr() to a static method, (optionally private as well) and you can remove RevereseString reverseStr = new RevereseString(); to save one line of code.

There is no need for a midIndex. You just need to reverse characters until the startIndex and lastIndex meet or cross. Thus you can remove int midIndex = 0 + (oldArray.length - 0)/2 ; and save another line of code.

Finally, you are not returning a new array; you are returning the original oldArray and assigning that object to newArray. In other words, as main() finishes, oldArray == newArray is true. You have reversed the oldArray in place; there is no need for a return value from reverseStr(), so you can eliminate at least another two lines of code.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.