Reputation: 23
I'm trying to create a method that takes in an array and then returns that array in reverse. The code I wrote returns the array in reverse, but, the first two values are now 0. Anyone know what I did wrong?
public static int[] reverse(int[] x)
{
int []d = new int[x.length];
for (int i = 0; i < x.length/2; i++) // for loop, that checks each array slot
{
d[i] = x[i];
x[i] = x[x.length-1-i]; // creates a new array that is in reverse order of the original
x[x.length-1-i] = d[i];
}
return d; // returns the new reversed array
}
Upvotes: 1
Views: 18578
Reputation: 11
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
System.out.println("The original Array: ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("The Reverse Array is: ");
for (int i = array.length - 1; i >= 0; i--) {
System.out.print(array[i] + " ");
}
Upvotes: 1
Reputation: 29
Here is a short way to do it.
public static int[] reverse(int[] x)
{
int[] d = new int[x.length]; //create new array
for (int i=x.length-1; i >= 0; i--) // revered loop
{
d[(x.length-i-1)]=x[i]; //setting values
}
return d; // returns the new reversed array
}
Upvotes: 3
Reputation: 347
Its simple mistake; you are coping reversed data in x; and returning d. If you will return x, you will get complete revered data.
d[i] = x[i]; // you are copying first element to some temp value
x[i] = x[x.length-1-i]; // copied last element to first; and respective...
x[x.length-1-i] = d[i]; // copied temp element to first element; and temp elements are nothing but array d
So ultimately you have created revered array inside x and not in d. If you will return x you got your answer. And d which is just half baked; so you get default value of 0 for remainign half array. :)
Upvotes: 1
Reputation: 311228
You are assigning values from an uninitialized array d
to x
- that's where the zeroes (default value for an int
in Java) are coming from.
IIUC, you're mixing two reversing strategies.
If you're creating a new array, you needn't run over half of the original array, but over all of it:
public static int[] reverse(int[] x) {
int[] d = new int[x.length];
for (int i = 0; i < x.length; i++) {
d[i] = x[x.length - 1 -i];
}
return d;
}
Alternatively, if you want to reverse the array in place, you don't need a temp array, only a single variable (at most - there are also ways to switch two int
s without an additional variable, but that's a different question):
public static int[] reverseInPlace(int[] x) {
int tmp;
for (int i = 0; i < x.length / 2; i++) {
tmp = x[i];
x[i] = x[x.length - 1 - i];
x[x.length - 1 - i] = tmp;
}
return x; // for completeness, not really necessary.
}
Upvotes: 7