I am trying to reverse an int array in Java.
This method does not reverse the array.
for(int i = 0; i < validData.length; i++)
{
int temp = validData[i];
validData[i] = validData[validData.length - i - 1];
validData[validData.length - i - 1] = temp;
}
What is wrong with it?
Your program will work for only
length = 0, 1
. You can try :Using the XOR solution to avoid the temp variable your code should look like
See this link for a better explanation:
http://betterexplained.com/articles/swap-two-variables-using-xor/
2 ways to reverse an Array .
Using For loop and swap the elements till the mid point with time complexity of O(n/2).
}
Using built in function (Collections.reverse())
}
Output : [6, 5, 4, 3, 2, 1]
Simple for loop!