-2

I was trying to reverse String using recursion as follows. But when I am calling reverse(arr,start++,end--) it is giving stackoverflow error.
I tried using reverse(arr,start+1,end-1) then it is working fine.

public class Reverse {
    public static void main(String[] args) {
        char inp[] = "TestString".toCharArray();
        int n = inp.length;
        reverse(inp, 0,n-1);
        System.out.println(String.valueOf(inp));


    }
    public static void reverse(char[] arr, int start, int end){
        if(start>=end)
            return ;
        char tmp;
        tmp = arr[start];
        arr[start] = arr[end];
        arr[end] = tmp;
        reverse(arr,start+1,end-1);//error line

    }

What is the problem with reverse(arr,start++,end--)? I want to know why value of start++ and end-- will not get passed to function.

js_248
  • 2,032
  • 4
  • 27
  • 38

1 Answers1

1

Have a look at this SO question

SO post-increment-and-pre-increment-concept

Post

reverse(arr,start++,end--) when you do this the incremented/decremented value will not be passed to recursive method, means you are calling the method with original value of start and end result in SO error

Pre

When you do reverse(arr,start+1,end-1) or reverse(arr,++start,--end) incremented and decremented value of start and end will be passed to recursive method.

While debugging in Eclipse IDE check the values of start and end in variables panel if not using IDE write start and end values to console in reverse method

Community
  • 1
  • 1
Saravana
  • 12,647
  • 2
  • 39
  • 57