Saturday, March 16, 2013

alpro: ringkasan 2



FUNDAMENTAL ALGORITHMS

EXCHANGING THE VALUES OF TWO VARIABLES

Algorithm Development

The problem of interchanging the values associated two variables involves a very fundamental mechanism that occurs in many sorting and data manipulation algorithms.

Algorithms 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.



Pascal Implementation

Procedure exchange  (var a,b : integer);
Var t : integer;
begin {save the original value of a then exchange  a and b}
{assert : a=a0^b=b0}
t:=a;
a:=b;
b:=t;
{assert : a=a0^b=a0}
end

Notes of Design

1.    The use of an intermediate temorary 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 the value dictated by the most recent assigment made to that variable.
3.   Working through the mechanism with a particular example can be a useful way of detecting design faults.
4.   A more common application of exchange involves two array elements.

Applications

Sorting algoritms.

No comments:

Post a Comment