XOR swap algorithm

http://en.wikipedia.org/wiki/XOR_swap_algorithm

Conventional swapping requires the use of a temporary storage variable. Using the XOR swap algorithm, however, no temporary storage is needed. The algorithm is as follows:

X := X XOR Y
Y := X XOR Y
X := X XOR Y

To understand it, think about the PLUS swap algorithm
a = a + b
b = a – b
a = a -b

interpret XOR: it is a binary PLUS operation without carry.

2 thoughts on “XOR swap algorithm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s