Jump to content

Swap by addition and subtraction

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 196.217.38.178 (talk) at 07:51, 22 November 2006 (Limitations). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

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

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.

Codes examples

C

A C function that implements the xor sby addition and subtraction algorithm:

void swap( int *x , int *y) {

	 *x = *x  + *y;
	 *y = *x - *y;
	 *x = *x - *y;

}