Almamy
Almamy

Reputation: 13

Printing Array elements through Recursion in java

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.

Upvotes: 0

Views: 708

Answers (1)

Tharindu Sathischandra
Tharindu Sathischandra

Reputation: 1994

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] + " "); 
          }
    }
}

Upvotes: 1

Related Questions