简体   繁体   中英

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}

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.

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)

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);
        
    }
    
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM