C++
programming
swap function
array manipulation
function optimization

Why is swap sometimes implemented by passing an array?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In languages like Java and C where primitives are passed by value, a swap(a, b) function cannot modify the caller's variables because it only receives copies. Passing an array (or using array indices) is a workaround: the function receives a reference to the array and can modify its elements in place. This is unnecessary in languages with pass-by-reference (C++ references, C pointers, Python objects) but is a common pattern in Java and JavaScript for primitive swaps.

The Problem: Pass-by-Value

java
1// Java — this does NOT work
2public static void swap(int a, int b) {
3    int temp = a;
4    a = b;
5    b = temp;
6    // a and b are local copies — caller's variables are unchanged
7}
8
9int x = 1, y = 2;
10swap(x, y);
11System.out.println(x + " " + y);  // Still "1 2"

Java passes primitives (int, double, boolean) by value. The function operates on copies, and changes do not propagate back to the caller.

Solution: Pass an Array

java
1// Java — this works
2public static void swap(int[] arr, int i, int j) {
3    int temp = arr[i];
4    arr[i] = arr[j];
5    arr[j] = temp;
6}
7
8int[] values = {1, 2};
9swap(values, 0, 1);
10System.out.println(values[0] + " " + values[1]);  // "2 1"

Java passes object references by value. The function receives a copy of the reference to the array, but both the caller and the function point to the same array. Modifying arr[i] changes the actual array contents.

Why This Works

 
1Caller:                Function:
2values ──→ [1, 2]  ←── arr (copy of reference)
3
4Both point to the same array in memory.
5arr[0] = arr[1] modifies the shared array.

The array itself is not copied — only the reference is. This is why element modifications are visible to the caller.

The Same Pattern in JavaScript

javascript
1// JavaScript — primitives are pass-by-value
2function swap(a, b) {
3    let temp = a;
4    a = b;
5    b = temp;
6    // Does nothing to caller's variables
7}
8
9let x = 1, y = 2;
10swap(x, y);
11console.log(x, y);  // 1 2 — unchanged
12
13// Fix: use an array
14function swapInArray(arr, i, j) {
15    [arr[i], arr[j]] = [arr[j], arr[i]];
16}
17
18let values = [1, 2];
19swapInArray(values, 0, 1);
20console.log(values);  // [2, 1]

JavaScript Destructuring Swap

In modern JavaScript, destructuring provides a cleaner alternative for local variables:

javascript
let a = 1, b = 2;
[a, b] = [b, a];
console.log(a, b);  // 2 1

This works inline without a function, but only for local variables.

Languages Where Arrays Are Not Needed

C++ — Pass by Reference

cpp
1// C++ — references let you swap directly
2void swap(int& a, int& b) {
3    int temp = a;
4    a = b;
5    b = temp;
6}
7
8int x = 1, y = 2;
9swap(x, y);
10// x = 2, y = 1 — works!
11
12// Or use std::swap from <algorithm>
13std::swap(x, y);

C++ references (int&) are aliases for the caller's variables. No array workaround needed.

C — Pass by Pointer

c
1// C — pointers to modify caller's variables
2void swap(int *a, int *b) {
3    int temp = *a;
4    *a = *b;
5    *b = temp;
6}
7
8int x = 1, y = 2;
9swap(&x, &y);
10// x = 2, y = 1

C does not have references, but pointers serve the same purpose. The caller passes addresses explicitly.

Python — Tuple Unpacking

python
1# Python — swap with tuple unpacking
2a, b = 1, 2
3a, b = b, a
4print(a, b)  # 2 1
5
6# For list elements
7lst = [1, 2, 3]
8lst[0], lst[2] = lst[2], lst[0]
9print(lst)  # [3, 2, 1]

Python does not need a swap function because tuple unpacking handles it natively.

Common Use Case: Sorting Algorithms

The array-based swap pattern appears naturally in sorting algorithms where you swap elements within an array:

java
1// Bubble sort — swapping array elements
2public static void bubbleSort(int[] arr) {
3    int n = arr.length;
4    for (int i = 0; i < n - 1; i++) {
5        for (int j = 0; j < n - i - 1; j++) {
6            if (arr[j] > arr[j + 1]) {
7                // Swap arr[j] and arr[j+1]
8                int temp = arr[j];
9                arr[j] = arr[j + 1];
10                arr[j + 1] = temp;
11            }
12        }
13    }
14}
15
16int[] data = {5, 3, 8, 1, 2};
17bubbleSort(data);
18// data = [1, 2, 3, 5, 8]

Here the array pattern is not a workaround — it is the natural approach because the data lives in an array.

Single-Element Array Wrapper (Hack)

In Java, some developers use a single-element array as a mutable container:

java
1// Hack to "swap" two primitives via arrays
2int[] xWrapper = {1};
3int[] yWrapper = {2};
4
5// Now pass the wrappers
6swap(xWrapper, yWrapper);
7
8static void swap(int[] a, int[] b) {
9    int temp = a[0];
10    a[0] = b[0];
11    b[0] = temp;
12}
13// xWrapper[0] = 2, yWrapper[0] = 1

This is ugly and rarely used. In practice, Java developers either swap elements within an existing array or restructure their code to avoid needing a swap function.

Common Pitfalls

  • Assuming Java passes objects by reference: Java passes object references by value. You can modify an object's fields through the reference, but you cannot make the caller's variable point to a different object. arr = new int[]{3, 4} inside a function does not affect the caller's array.
  • XOR swap trick: a ^= b; b ^= a; a ^= b; swaps without a temp variable but fails when a and b are the same memory location (result is 0). It is also slower than a temp variable on modern CPUs. Avoid it.
  • Forgetting bounds checking: swap(arr, i, j) should verify that i and j are within bounds. ArrayIndexOutOfBoundsException (Java) or undefined behavior (C/C++) results from out-of-bounds access.
  • Using swap on immutable types: In Java, String and wrapper types (Integer, Double) are immutable. Even with an array, you cannot swap two String variables without reassignment. You can swap array elements containing strings, but not standalone string variables.
  • Overcomplicating in languages with native swap: C++ has std::swap, Python has tuple unpacking, Kotlin has also. Do not implement array-based swap in these languages — use the native mechanism.

Summary

  • Passing an array to a swap function works because Java/JavaScript pass the array reference by value, allowing element modification
  • This pattern is needed in languages where primitives are pass-by-value (Java, JavaScript, C)
  • C++ uses references (int&), C uses pointers (int*), and Python uses tuple unpacking (a, b = b, a)
  • The array swap pattern is most natural in sorting algorithms where data already lives in an array
  • Use the language's native swap mechanism when available — std::swap (C++), tuple unpacking (Python), destructuring (JavaScript)

Course illustration
Course illustration

All Rights Reserved.