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 =
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:
public static int[] reverseAnArrayInSpace(int[] array) {
int startIndex = 0;
int endIndex = array.length - 1;
while(startIndex < endIndex) {
int temp = array[endIndex];
array[endIndex] = array[startIndex];
array[startIndex] = temp;
startIndex++;
endIndex--;
}
return array;
}
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:
public static int[] reverseAnArrayWithAuxiliaryArray(int[] array) {
int[] reversedArray = new int[array.length];
for(int index = 0; index < array.length; index++) {
reversedArray[index] = array[array.length - index -1];
}
return reversedArray;
}
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:
public static Integer[] reverseAnArrayWithCollections(Integer[] array) {
List arrayList = Arrays.asList(array);
Collections.reverse(arrayList);
return arrayList.toArray(array);
}