J.Lin
J.Lin

Reputation: 13

Using recursive function to reverse the second half of an array

I am a beginner of Java. I know how to print a reversed array but I don't know how to print half of it. For example:

Original Array A = {1,2,3,4,5,6,7,8,9,0}

After the function:

Transformed Array A' = {1,2,3,4,5,0,9,8,7,6}

Upvotes: 0

Views: 5116

Answers (3)

Please find the perfect solution guys!!!

import Arrays & Scanner packages

public static void main(String[] args) {

    Scanner size = new Scanner(System.in);
    System.out.println("Enter Array Size : ");
    int arraySize = size.nextInt();
    
    Scanner data = new Scanner(System.in);
    System.out.println("Enter Array Data : ");
    int arrayData[] = new int[arraySize];
    
    for(int inputLoop = 0; inputLoop < arraySize; inputLoop++) {
        
        arrayData[inputLoop] = data.nextInt();
        
    }
    
    System.out.println("Original Array : " + Arrays.toString(arrayData));
    
    int centerPoint = arrayData.length / 2;
    int endPoint = arrayData.length - 1;
    
    reverse(arrayData, centerPoint, endPoint);
    
    System.out.println("Transformed Array : " + Arrays.toString(arrayData));
    
    data.close();
    size.close();

}

private static void reverse(int[] arrayData, int centerPoint, int endPoint) {

    if(centerPoint > endPoint || centerPoint == endPoint) {
        
        return;
        
    }
    else {
        
        arrayData[centerPoint] = arrayData[centerPoint] - arrayData[endPoint];
        arrayData[endPoint] = arrayData[centerPoint] + arrayData[endPoint];
        arrayData[centerPoint] = arrayData[endPoint] - arrayData[centerPoint];
        
        reverse(arrayData, ++centerPoint, --endPoint);
        
    }
    
}

}

Upvotes: 0

Nikita Mantri
Nikita Mantri

Reputation: 142

private void reverse(int[] ar, int i, int j) {
   if(i>j)
     return;
   else{
     int temp = ar[i];
     ar[i] = ar[j];
     ar[j] = temp;
     reverse(ar, ++i, --j);
   }
}

Call reverse(ar, (ar.length/2), ar.length-1) from the main method.

Upvotes: 3

Kajal
Kajal

Reputation: 739

Try the following steps,

  1. Find the length of the array - N
  2. Create another array of size - N
  3. Find the Half - n
  4. Copy first n elements
  5. Break, start from last(index to the last element) and copy the elements til nth location (Note index pointer should be decremented)

Upvotes: 0

Related Questions