Swap two array elements without a temporary variable
Implement Swap(a, i, j) that swaps a[i] and a[j] IN PLACE WITHOUT a temporary variable. Requirements: prefer the tuple swap (a[i], a[j]) = (a[j], a[i]). If asked about the arithmetic or XOR tricks, note they break when i == j (they zero the element). Swapping an index with itself must leave the array unchanged.
public static void Swap(int[] a, int i, int j)
{
// your code here
}
Write the implementation.
Use a tuple swap: (a[i], a[j]) = (a[j], a[i]). The right side is evaluated fully before either assignment, so both elements exchange safely — even when i == j, where it just rewrites the same value. It needs no temp and avoids the arithmetic/XOR tricks that zero the element on self-swap.
- ✗Using XOR or add/subtract, which zero out the element when
i == j - ✗Believing arithmetic swap is safe — it can overflow
intfor large values - ✗Sneaking in two local copies, which is just a renamed temporary variable
- →Exactly why does the XOR swap zero the element when
i == j? - →How does the tuple swap evaluate the right-hand side before assigning?
Task
Swap a[i] and a[j] without a temporary variable.
public static void Swap(int[] a, int i, int j)
{
(a[i], a[j]) = (a[j], a[i]); // right-hand side is evaluated first
}
How it works
C#'s tuple assignment first evaluates the right-hand side (a[j], a[i]) fully into a temporary tuple, then unpacks it back into a[i] and a[j]. So both values are exchanged at once and neither is lost — no separate temporary variable is needed.
A key advantage is safety when i == j. Then both sides refer to the same element, and the swap simply rewrites it with the same value: the array is unchanged. The "clever" no-temp tricks break here:
- XOR (
a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j];) doesx ^ x = 0wheni == j— the element is zeroed. - Arithmetic (
+/-) also zeroes the element wheni == j, and can additionally overflowintfor large values.
The tuple swap avoids both traps, reads clearly, and runs in O(1).