0
public static void displayArray(int array[], int first, int last) {
  if (first == last)
    System.out.print(array[first] + " ");
  else {
    int mid = (first + last) / 2;
    displayArray(array, first, mid);
    displayArray(array, mid + 1, last);
  } // end if
}

-Can anyone please explain to me how this method is working. I know that it prints the elements in the array, but I am confused how since there is a no print statement in the recursive case.

3
  • 1
    Make an array of 4 elements. Work through the code on a whiteboard or a piece of paper. Commented Jun 12, 2021 at 1:50
  • 2
    Write it out on a piece of paper. E.g. try out with initial values array = { 1, 3, 7 }, first = 0, last = 2, then follow the logic and write down what the 2 recursive calls will be. Then for each of those, repeat it. Commented Jun 12, 2021 at 1:51
  • You can use a debugger and see what happens easily. Add some break points and debug it. IDEs like Intellij Idea provide nice debugging interfaces? Commented Jun 12, 2021 at 2:28

1 Answer 1

1

Let's say you have an input array like [1, 2, 3, 4, 5],

int[] array = new int[]{1, 2, 3, 4, 5};
displayArray(array, 0, array.length - 1);

Now the functions are called like this way,

displayArray(array, 0, 4) {
    int mid = (0 + 4) / 2 = 2;
    displayArray(array, 0, 2) { // first, mid
       int mid = (0 + 2) / 2 = 1;
        displayArray(array, 0, 1) { // first, mid
            int mid = (0 + 1) / 2 = 0;
            displayArray(array, 0, 0) { // first, mid
              System.out.print(array[0] + " ");      
            }       
            displayArray(array, 1, 1) { // mid + 1, last
              System.out.print(array[1] + " "); 
            }
        }       
        displayArray(array, 2, 2) { // mid + 1, last
            System.out.print(array[2] + " "); 
        }
    }       
    displayArray(array, 3, 4) { // mid + 1, last
          int mid = (3 + 4) / 2 = 3;
          displayArray(array, 3, 3) { // first, mid
              System.out.print(array[3] + " "); 
          }       
          displayArray(array, 4, 4) { // mid + 1, last
              System.out.print(array[4] + " "); 
          }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.