0

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}

3 Answers 3

3
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.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought your code would be useful but I got an ArrayIndexOutOfBoundsException when I used your code so what is going on?
0

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)

Comments

0

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

}

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.