Reverse an array in place
It is easy to reverse an array if we are allowed to create another array, and then iterate over the original array in reverse and add each element to the newly created array.
But, here we are asked not to create and use any other data structure. So we need to do everything in place.
But, here we are asked not to create and use any other data structure. So we need to do everything in place.
The solution is to just loop over the array and use a two-pointer technique. One pointer (i) will start from the beginning of the array, and another pointer (j) will start from the end.
And we will just swap the elements, eg. first with last element, second first with second last, etc. Until we get to the position where i > j.
Here is the complete Java program:
public class DevPrimer {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
reverse(arr);
Arrays.stream(arr).forEach(num -> System.out.print(num + " "));
}
public static void reverse(int[] arr) {
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
The time complexity is O(n/2) or O(n) because it needs to iterate over almost half the elements and perform n/2 swapping as well.
The space complexity is O(1) since we are not creating any new data structure , hence we don't need any extra space in memory.
The space complexity is O(1) since we are not creating any new data structure , hence we don't need any extra space in memory.
No comments:
Post a Comment