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 =
Wouldn't doing it this way be much more unlikely for mistakes?
int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] temp = new int[intArray.length];
for(int i = intArray.length - 1; i > -1; i --){
temp[intArray.length - i -1] = intArray[i];
}
intArray = temp;
Using the XOR solution to avoid the temp variable your code should look like
for(int i = 0; i < validData.length; i++){
validData[i] = validData[i] ^ validData[validData.length - i - 1];
validData[validData.length - i - 1] = validData[i] ^ validData[validData.length - i - 1];
validData[i] = validData[i] ^ validData[validData.length - i - 1];
}
See this link for a better explanation:
http://betterexplained.com/articles/swap-two-variables-using-xor/
If working with data that is more primitive (i.e. char, byte, int, etc) then you can do some fun XOR operations.
public static void reverseArray4(int[] array) {
int len = array.length;
for (int i = 0; i < len/2; i++) {
array[i] = array[i] ^ array[len - i - 1];
array[len - i - 1] = array[i] ^ array[len - i - 1];
array[i] = array[i] ^ array[len - i - 1];
}
}
With Commons.Lang, you could simply use
ArrayUtils.reverse(int[] array)
Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.
Solution with o(n) time complexity and o(1) space complexity.
void reverse(int[] array) {
int start = 0;
int end = array.length - 1;
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
In case of Java 8 we can also use IntStream
to reverse the array of integers as:
int[] sample = new int[]{1,2,3,4,5};
int size = sample.length;
int[] reverseSample = IntStream.range(0,size).map(i -> sample[size-i-1])
.toArray(); //Output: [5, 4, 3, 2, 1]