Reverse the order of elements of an array without allocating a second array.
Swap elements from both ends toward the middle with two pointers — O(n) time, O(1) space. This is the array analog of string reversal and the building block for the rotate-by-k trick.
public static void reverse(int[] a) {
int i = 0, j = a.length - 1;
while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; }
}function reverse(a) {
let i = 0, j = a.length - 1;
while (i < j) { [a[i], a[j]] = [a[j], a[i]]; i++; j--; }
return a;
}def reverse(a):
i, j = 0, len(a) - 1
while i < j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
return aIn-place reversal is a fundamental primitive reused by rotation, palindrome checks, and undo/redo style buffers.
What is the advantage of the in-place swap over building a new reversed array?