Swap by addition and subtraction
Appearance
Standard swapping algorithms require the use of a temporary storage area - standard intuitive algorithms to swap x and y involve:
- copying y aside to a temporary storage area
- setting y to be x
- copying the temporary storage value back to x.
However, this algorithm requires only the mathematical operations of addition and subtraction. The algorithm follows (where A and B are the values stored in the variables X and Y respectively):
- X has A, Y has B.
- Step 1: Add X and Y and store in X
- Now X has A + B, Y has B.
- Step 2: Subtract Y from X and store in Y
- Now X has A + B, Y has A.
- Step 3: Subtract Y from X and store in X
- Now X has B, Y has A. Swap done.
The algorithm looks much simpler when it is written in pseudocode.
- X := X + Y
- Y := X - Y
- X := X - Y
Limitation: Due to the addition operation in the first step, this swap algorithm would fail for the case of (A+B) overflow, i.e., when the sum exceeds the maximum allowable number for a given number of bits.