- Forward


Swapping
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Frequently:
    • We need to swap the contents of two variables
  • A Context:
    • A fantasy role playing game in which players commonly acquire items of various kinds (e.g., weapons, spells, gold, food)
  • An Example of a Swap:
    • As the game progresses, two players meet and realize that it would benefit both of them to swap their swords
Review
Back SMYC Forward
  • The Assignment Operator:
    • Stores the right side operand in the memory location identified by the left side operand
  • Variables:
    • Can only hold one "thing"
Review (cont.)
Back SMYC Forward
javaexamples/programmingpatterns/Swapping.java (Fragment: assignment)
 
Swapping_Assignment
A Defective Algorithm (cont.)
Back SMYC Forward
javaexamples/programmingpatterns/Swapping.java (Fragment: badswap)
 
Swapping_BadSwap
Thinking About the Problem
Back SMYC Forward
  • Suppose:
    • You have Caladbolg in your right hand and Durendal in your left hand, and you want to swap them
  • To Make Progress:
    • You need a place to temporarily store one of the swords
The Pattern
Back SMYC Forward
  • The Idea:
    • Use another variable to temporarily hold the contents of one variable
  • javaexamples/programmingpatterns/Swapping.java (Fragment: swap)
     
The Pattern (cont.)
Back SMYC Forward
Swapping
Example
Back SMYC Forward
javaexamples/programmingpatterns/Swapping.java (Fragment: swordswap)
 
The Example (cont.)
Back SMYC Forward
Swapping_SwapSteps
A Warning
Back SMYC Forward
  • The Idea:
    • Write a method that swaps the contents of its two parameters
  • The Issue:
    • To understand what is and isn't possible one must understand parameter passing mechanisms
There's Always More to Learn
Back -