Jump to content

Swap by addition and subtraction

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Alphachimpbot (talk | contribs) at 20:37, 28 September 2006 (BOT - updating merge tags to appear in Category:Merge by month). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Template:Merge-date

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.