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?
There are two ways to have a solution for the problem:
1. Reverse an array in space.
Step 1. Swap the elements at the start and the end index.
Step 2. Increment the start index decrement the end index.
Step 3. Iterate Step 1 and Step 2 till start index < end index
For this, the time complexity will be O(n) and the space complexity will be O(1)
Sample code for reversing an array in space is like:
2. Reverse an array using an auxiliary array.
Step 1. Create a new array of size equal to the given array.
Step 2. Insert elements to the new array starting from the start index, from the given array starting from end index.
For this, the time complexity will be O(n) and the space complexity will be O(n)
Sample code for reversing an array with auxiliary array is like:
Also, we can use the Collections API from Java to do this.
The Collections API internally uses the same reverse in space approach.
Sample code for using the Collections API is like:
With Guava:
This will help you
This is how I would personally solve it. The reason behind creating the parametrized method is to allow any array to be sorted... not just your integers.
I hope you glean something from it.
Solution with o(n) time complexity and o(1) space complexity.
There are already a lot of answers here, mostly focused on modifying the array in-place. But for the sake of completeness, here is another approach using Java streams to preserve the original array and create a new reversed array: