ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Bitwise Swap of Two Integers

C

Goal -- WPM

Ready
Exercise Algorithm Area
1#include <stdio.h>
2
3void swap(int* a, int* b) {
4if (a == NULL || b == NULL || a == b) return;
5*a = *a ^ *b;
6*b = *a ^ *b;
7*a = *a ^ *b;
8}
9
10int main() {
11int x = 5, y = 10;
12printf("Before swap: x = %d, y = %d\n", x, y);
13swap(&x, &y);
14printf("After swap: x = %d, y = %d\n", x, y);
15
16int p = -7, q = 23;
17printf("Before swap: p = %d, q = %d\n", p, q);
18swap(&p, &q);
19printf("After swap: p = %d, q = %d\n", p, q);
20
21int r = 100, s = 100;
22printf("Before swap: r = %d, s = %d\n", r, s);
23swap(&r, &s);
24printf("After swap: r = %d, s = %d\n", r, s);
25return 0;
26}
Algorithm description viewbox

Bitwise Swap of Two Integers

Algorithm description:

This C code demonstrates swapping two integer variables using the bitwise XOR operation, a classic trick that avoids the need for a temporary variable. This technique is useful in low-level programming or when optimizing for minimal memory usage.

Algorithm explanation:

The XOR swap algorithm relies on the properties of the XOR operation: `A ^ A = 0` and `A ^ 0 = A`. The three steps are: 1. `*a = *a ^ *b;` (The new `*a` holds the XOR sum of original `*a` and `*b`). 2. `*b = *a ^ *b;` (This is `(*a ^ *b) ^ *b`, which simplifies to `*a ^ (*b ^ *b)` or `*a ^ 0`, resulting in the original value of `*a`). 3. `*a = *a ^ *b;` (This is `(*a ^ *b) ^ *a`, which simplifies to `(*a ^ *a) ^ *b` or `0 ^ *b`, resulting in the original value of `*b`). The time complexity is O(1) as it's a fixed sequence of operations. Space complexity is O(1) as no extra variables are used. An edge case is when `a` and `b` point to the same memory location, which is handled by an initial check.

Pseudocode:

function swap(pointer_a, pointer_b):
  if pointer_a is null or pointer_b is null or pointer_a equals pointer_b:
    return
  *pointer_a = *pointer_a XOR *pointer_b
  *pointer_b = *pointer_a XOR *pointer_b
  *pointer_a = *pointer_a XOR *pointer_b