Technique: How to interchange the values of variables

To interchange the values of two variables X and Y, we can write

W = Y; Y = X; X = W

In Rexx we can exchange words X and Y by statement

parse value X Y with Y X

Another (general) way is using of the VALUE function. The VALUE function returns the value of the symbol named by the first argument and optionally assigns it a new value.

X = VALUE('Y', X)

And the values of sequence X, Y, Z can be rearranged to Z, X, Y (ie. the new value of Y is to be the original value of X, etc.) by the fragment

W = Z; Z = Y; Y = X; X = W

A general solution of this problem, for I-variables A.1,A.2,...,A.I (I>=2), follows


W = A.I
do J = I - 1 to 1 by -1
  Jp1 = J + 1; A.Jp1 = A.J
end
A.1 = W

We use this technique for programming the insertion sort algorithm.


do I = 2 to N
  Im1 = I - 1
  if A.I < A.Im1 then do
    W = A.I
    do J = I - 1 by - 1 until A.Jm1 <= W | J = 1
      Jp1 = J + 1; A.Jp1 = A.J; Jm1 = J - 1
    end
    A.J = W
  end
end

 

CONNECTIONS


Cover Contents Index Main page Rexx page   Mail

last modified 1st August 2001
Copyright © 2000-2001 Vladimir Zabrodsky
Czech Republic