Swap by addition and subtraction
From Wikipedia, the free encyclopedia
This article details an algorithm to swap two variables in computer programming.
The standard algorithm require the use of a temporary storage area. However, this algorithm requires only that mathematical operations addition and subtraction be defined.
To illustrate this operation, we assume we want to swap the values of two variables, X and Y. We assume their current values are A and B, respectively. In pseudocode:
//the operation X := X + Y //now X = A + B Y := X - Y //now Y = X - B = (A + B) - B = A X := X - Y //now X = (A + B) - Y = (A + B) - A = B //swap complete
[edit] Limitations
This algorithm only works if the variables to be swapped are numeric and can be added or subtracted. It would be nonsensical to attempt to add and subtract two strings or linked lists, for example.
Due to the addition operation in the first step, this swap algorithm is prone to overflow when the swapped operands are of a fixed size.
[edit] Codes examples
[edit] C
A C function that implements the swap by addition and subtraction algorithm:
void swap(int *x, int *y) { *x = *x + *y; *y = *x - *y; *x = *x - *y; }