Java Array Reverse logic

Viewed 99
import java.util.Scanner;

public class Reverse {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int arr[] = new int[5];
        System.out.println("Enter the values in the array");
        for (int i = 0; i < arr.length - 1; i++) {
            arr[i] = sc.nextInt();
        }

        for (int i = 0; i < 5; i++) {
            int temp;
            int j = 4;
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            j--;
            System.out.println(arr[i]);
        }

    }
}

This logic is not reversing the array of integers why?????

input 123

output is 0123

3 Answers

One approach you may try here is to simply swap each element in the array across the middle position:

int[] arr = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(arr));
for (int i=0; i < arr.length/2; i++) {
    int temp = arr[i];
    int j = arr.length - i - 1;
    arr[i] = arr[j];
    arr[j] = temp;
}
System.out.println(Arrays.toString(arr));

This prints:

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

The problem with your current logic is largely this line:

int j = 4;

You assign the upper pointer to the array as 4, for each iteration of the loop. Instead, the value j should be initialized as 4 outside of the loop, and then decremented during each iteration. But, I would probably use the version I gave above.

There are several problems in your code:

  1. You need to initialize j before the array. If you initialize it to 4 inside the array, then you will always swap the last element with the i'th element and then decrease j.

  2. With i stop at arr.length / 2. Imagine this scenario:

You have the following set: 1 2 3 4 5

If you go to the end, then these will be the states:

1 2 3 4 5

5 2 3 4 1

5 4 3 2 1

5 4 3 2 1

1 4 3 2 5

1 2 3 4 5

because you swap correctly the values until you reach half of the data set and then you swap it back. You will need to stop at half way.

As the last element is not saved it is set to 0. So the array that is saved is 12340 not 1234

The reversing logic is incorrect as you are always swapping with the last element.

1st iteration - 1 swaps with 0 - New string -> 02341
2nd iteration - 2 swaps with 1 - New string -> 01342
3rd iteration - 3 swaps with 2 - New string -> 01243
4th iteration - 4 swaps with 3 - New string -> 01234

If you print out the whole string each time it'll make sense. As you are printing only the swapped character in each iteration it is unclear what is happening

Related