Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

The array is not reversing

According to this piece of code I must get a reverse array but I’m still getting the non-reversed.

public class Reversing_array {
    public static void reverse_arr(int arr[]) {
        int n = arr.length - 1;
        for (int i = 0; i < arr.length; i++) {
            int temp = arr[i];
            arr[i] = arr[n - i];
            arr[n - i] = temp;
        }
    }

    public static void main(String[] args) {
        int arr[] = { 10, 20, 30, 40, 50 };
        reverse_arr(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

I performed a dry run of it, but still didn’t reached to the mistake.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you have an array of four elements, and run swaps four times:

1 2 3 4 // initial state
4 2 3 1 // first swap
4 3 2 1 // second swap <- this is what we want
4 2 3 1 // third swap  <- but we kept going...
1 2 3 4 // fourth swap <- and going...

You want to swap arr.length / 2 times to avoid re-swapping back into the original order. If the length of the array is odd, this will avoid swapping the middle element, but that’s okay.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading