2

I am attempting to reverse an Array of int values. It does not seem to be doing it correctly. You will note that I am printing in different ways, like Array.toString() and also using println.

The original array prints:

1 4 9 16 9

I need it to print:

9 16 9 4 1

Here is my code:

import java.util.Arrays;

public class ReverseArray {
    public static void main(String[] args) {
        int[] data = { 1, 4, 9, 16, 9 };
        reverseArray(data);
        int[] dataR = reverseArray(data);
        System.out.println("Reveresed data " + Arrays.toString(dataR));
    }

    public static int[] reverseArray(int[] data) { // returns the reverse of the
                                                    // array data
        // int [] data = new int[5];
        int[] reversedData = new int[data.length];

        data[0] = 1;
        data[1] = 4;
        data[2] = 9;
        data[3] = 16;
        data[4] = 9;

        System.out.println(Arrays.toString(data));
        for (int i = 0; i < data.length - 1; i++) {
            System.out.println("Original Array: " + data[i]);
        }

        int reveresedData[] = data;

        for (int i = 0; i < reveresedData.length - 1; i++) {
            reversedData[(data.length - 1) - i] = data[i];
            System.out.println(reveresedData[i]);
        }
        return reveresedData;
    }

}
3
  • Why are you having so much of duplicate code, and re-assignment of same thing again and again? Commented Feb 13, 2013 at 18:33
  • Most part of your code seem unnecessary.. Commented Feb 13, 2013 at 18:34
  • Its a class session. Going through loops, arrays, different ways to print arrays and more. Commented Feb 13, 2013 at 18:40

4 Answers 4

2

The problem is that the following:

int reveresedData[] = data;

makes reveresedData point to the same array as data. Instead, you need to create a new array (or change the algorithm so that it reverses the array in place).

To create a new array, you could use either of:

int reveresedData[] = new int[data.length];
int reveresedData[] = data.clone();
Sign up to request clarification or add additional context in comments.

1 Comment

i would have recommended Arrays.copyOf(...)
1

(Using For each loop : Smarter way) Create a method as follows:

 private int[] reverseArray(int [] array1){
        int index=array1.length;
        int [] array2 = new int[index];
        for(int i:array1){
            array2[index-1]= i;
            index--;
        }
        return array2;    
}

And call it like:

int [] array1 = {1,2,3};
int reversedArray[] = reverseArray(array1);

Thats it.

8 Comments

how is a for each a smarter way than a regular for loop?
I seem to be getting an out of bounds exception? array2[index]= i;
I have Edited Answer. There was a small counter mistake. now test it, It should be running now as a charm. i dint runt it, i have only written the logic here so Also please let me know after running, if it helps you.
it is called "for each loop", and not the short form, it is new loop introduced i java 6, but does the same work as for(int i = 0; i < array1.length; i++) but reduces human efforts. just search on google about java for each loop. it's syntex is like- for(ContentTypeOfArray x : ArrayName){Here for each iteration you will get content in x}. I always prefer to use for each loop over normal for loop because it minimizes human errors of maintaining start index, loop limit, increment etc.
For that algorithm to work, did you write it out first, or has this come with great experience? I only ask this as I am just starting out with regards to programming.
|
1

should be something like this:

int reversed[] = new int[data.length];

This will allocate space for a new array that you can fill with the values of data in reverse order.

for (int i = 0,j=reversed.length-1; i < reversed.length-1; i++;j--){
        reversed[i]=data[j];
    }

1 Comment

My syntax may be off in the for loop, as i didnt type this out in a web ide.
1

Here is a basic approach to reverse array of any size. It reverses the original array.

public class ReverseMyArray {
public static int[] reverseArray(int[] array) {
    for(int i=0; i<array.length/2; i++) {
        int temp = array[i];                    // temp is a temporary variable of type int
        array[i] = array[array.length-1-i];
        array[array.length-1-i] = temp;
    }
    return array;
}

public static void main(String[] args) {
    int[] array = {1,4,9,16,9};
    int[] newArray = reverseArray(array);
    for(int i=0; i<newArray.length; i++) {          
        System.out.print(newArray[i]+" ");      // Print the reversed array values
    }
}
}

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.