Information Technology Center

Algorithms III

BSS Main | Previous Lesson | Next Lesson

Posted : February 27th, 2010

A Swap Algorithm

Study this algorithm carefully.

The Swap Algorithm Problem Defined

Write an algorithm to read two integer values A and B then interchange or swap them in memory. Finally print the output.

Does this seem difficult? It is not. I am sure if you give it a some careful thought you can come up with a solution. To help you on your way I will restate the problem using something that may be close to your heart. What if I gave you two drinking glasses. The first glass containing milk and the other containing water and ask you to pour the water into the first drinking glass and the milk into the second drinking glass. Can you solve that problem?

Most likely you would suggest that I get a third container into which I should pour the milk before pouring the water into the first drinking glass. We must use the same procedure for a swap algorithm. Although I only mentioned swapping two values a third variable is needed to perform this task.


The Swap Algorithm Solution

         Begin
               a = 0, b = 0, c = 0
                  Read  a, b  
                   c = a            
                   a = b
                   b = c
               Print a, b
           End

You may have to study this algorithm a while before you actually understand it. Remember to think of a, b, and c as glasses. Glass a has milk. Glass b has water and glass c is empty. We pour from a into the empty c glass. Now glass a is empty so we can then pour from glass b into glass a. This now leaves glass b empty. Finally we pour from glass c into glass b.

If you have difficulty you should get three glasses and try out the solution above. The contents of each glass is not what is important the concept is though.


Algorithm Problem Four

Write an algorithm to read in two numbers into A and B. The algorithm should store the smaller value in A and the larger value in B, and then print A and B.

Solution to Problem Four

         Begin
                 A=0, B=0, temp=0             
           
                Input A, B
              If A > B
                    temp = A
                       A  = B
                   B = temp
              endif
          Print A, B
      End

Let us suppose the user enters the numbers 5 and 12. The first number 5 will be assigned to the variable A and the second number 12 will be assigned to B. They are already in the required order. No swapping is necessary. However, if the number 12 in entered first and the number 5 is entered after then the swap is necessary. If you examine this algorithm carefully you will observe that processing takes place only if A is greater than B. If A is not greater than B then the values are printed in the same order in which they were entered without taking any action.


Registered Students may email The Tutor at tutordam@yahoo.com with your questions and or comments.