Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to reverse an array in Java [duplicate]

Tags:

java

arrays

I am a newbie in Java. I wrote this program to reverse an array:

public class Reverse {

    public static void main(String[] args) {

        int num[] = {55, 2, 37, 9, 8};

        System.out.println("Original array is: ");
        for (int i : num)
            System.out.print(i + " ");

        for (int i = 1 ; i  != 5; i++) {
            num[i - 1] = num[num.length - i];
        }

        System.out.println("\nReversed array is: ");
        for (int i : num)
            System.out.print(i + " ");

        System.out.println(" ");

    }
}

But I am getting the below result. Do you guys know what I am doing wrong?

Original array is: 55 2 37 9 8 Reversed array is: 8 9 37 9 8

like image 328
user2056083 Avatar asked Jun 06 '26 13:06

user2056083


1 Answers

You can swap the front and back elements of the array.

This way saves space.

int[] array = {1, 2, 3, 4, 5};

for (int i = 0; i < array.length/2; i++)
{
   int tmp = array[i];
   array[i] = array[array.length - i - 1];
   array[array.length - i - 1] = tmp;
}

// array is now reversed in place

If you don't want to change the contents of the original array, you can copy it into a new array of equal length:

int[] array = {1, 2, 3, 4, 5};
int[] reversedArray = new int[array.length];

for (int i = 0; i < array.length; i++)
{
   reversedArray[i] = array[array.length - i - 1];
}

// print out contents of reversedArray to see that it works
like image 198
corgichu Avatar answered Jun 09 '26 02:06

corgichu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!