EXCHANGING THE VALUES
OF TWO VARIABLE
Problem: Given two variable, a and b, exchange the values
assigned to them.
Algorithm development
The problem of interchanging the values associated with two
variables involves very fundamental mechanism that occurs in many sorting and
data manipulation algorithms. To define the problem more clearly we will
examine a specific example.
Considers
that the variables a and b are assigned values as outlined below. That is :
This means variable a
contains the value 721, and variable b
contains 463. Our tash is to replace the contents of a with 463, and contents of b
with 721. We want to end up with the cinfuguration below :
To change the values of a variable we can use the assignment
operator. Because we want a to assume
the value currently belonging to b, and b too. We could perhaps make the
exchange with the following assignment
Where “:=” is the assignment operator. In (1) “:=” causes
the value stored in memory cell b to be copied into memory cell a. We started out with the configuration
Then after execution of the assignment a:=b we have
In executing step (2) a
is not changed while b takes on
the values that currently belongs to a. The Problem arises because in making the assignment:
It is this value that we want b to finally assume. Our problem must therefore be stated more
carefully as:
New value of b := new value of a.
To solvethis exchange problem we
need to find a way of not destroying “the
old value of a” when we make the
assignment
The Steps to do this
are:
After these:
It is this
value that we need for assignment to b. We
can therefore make the assignment :
Now
we see that a and b have now been interchanged as required. The exchange
procedure can now be outlined.
Algorithm description
1. Save
the original value of a in t
2. Assign
to a the original value of b.
3. Assign to b the original value of a that is stored in t
Notes on design
1. The
use of an intermediate temporary variable allows the exchange of two variables
to proceed correctly.
2. This
example emphasizes that at any stage in a computation a variable always assumes
that value dictated by the most recent assignment made to that variable.
3. Working
through the mechanism with a particular example can be a useful way to
detecting design faults.
4. A
more common application of exchange involves two array elements (e.g. a[i] and
a[j]).