Monday, December 30, 2013

Swap using addition and subtraction operation

Suppose a bus stops at a terminal. All the people in the bus want to get down and all the people standing out want to get in and there is only one exit and entry door in the bus.
In this case it would be easier for everyone in the bus to get down and then everyone standing outside to get in. At one point all the persons are standing outside bus.

The above example is similar case is similar to swap using addition and subtraction operation.
Swap
a=a+b
b=a-b
a=a-b

Say
a=5,b=3
a=5+3=8  [a=a+b]
b=8-3=5  [a=a-b]
a=8-5=3  [a=a-b]
a=3,b=5

The problem with this kind of swap is that it is applicable only to numeric data. Addition of numbers can result in a number greater than the size the variable or memory location can hold leading to overflow error.

No comments:

Post a Comment