ArticleslgStudy

computer science

Swap (computer programming)

Swap (computer programming) is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Swap (computer programming) rather than just read about it. In short: In computer programming, the act of swapping two variables mutually exchanges their values. Usually, this is done with the data in memory.

Swap (computer programming) — main illustration
Swap (computer programming) — illustration

Key takeaways

  • Swap (computer programming) belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Swap (computer programming) to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Swap (computer programming) from memory before moving on to harder problems.

Reference excerpt

In computer programming, the act of swapping two variables mutually exchanges their values. Usually, this is done with the data in memory. For example, in a program, two variables may be defined thus (in pseudocode):

After swap() is performed, x will contain the value 0 and y will contain 1; their values have been exchanged. This operation may be generalized to other types of values, such as strings and aggregated data types. Comparison sorts use swaps to change the positions of data. In many programming languages the swap function is built-in. In C++ overloads are provided allowing std::swap to exchange some large structures in O(1) time.

Using a temporary variable

The simplest and probably most widely used method to swap two variables is to use a third temporary variable:

define swap (x, y) temp := x x := y y := temp

While this is conceptually simple and in many cases the only convenient way to swap two variables, it uses extra memory. Although this should not be a problem in most applications, the sizes of the values being swapped may be huge (which means the temporary variable may occupy a lot of memory as well), or the swap operation may need to be performed many times, as in sorting algorithms. In addition, swapping two variables in object-oriented languages such as C++ may involve one call to the class constructor and destructor for the temporary variable, and three calls to the copy constructor. Some classes may allocate memory in the constructor and deallocate it in the destructor, thus creating expensive calls to the system. Copy constructors for classes containing a lot of data, e.g. in an array, may even need to copy the data manually.

XOR swap

XOR swap uses the XOR operation to swap two numeric variables. It is generally touted to be faster than the naive method mentioned above; however it does have disadvantages. XOR swap is generally used to swap low-level data types, like integers. However, it is, in theory, capable of swapping any two values which can be represented by fixed-length bitstrings.

Swap through addition and subtraction

This method swaps two variables by adding and subtracting their values. This is rarely used in practical applications, mainly because:

It can only swap numeric variables; it may not be possible or logical to add or subtract complex data types, like containers. When swapping variables of a fixed size, arithmetic overflow becomes an issue. It does not work generally for floating-point values, because floating-point arithmetic is non-associative.

Swapping containers Containers which allocate memory from the heap using pointers may be swapped in a single operation, by swapping the pointers alone. This is usually found in programming languages supporting pointers, like C or C++. The C++ Standard Library overloads its built-in std::swap(x, y) function to exchange the contents of containers efficiently this way. As pointer variables are usually of a fixed size (e.g., most desktop computers have pointers 64 bits long), and they are numeric, they can be swapped quickly using XOR swap.

Parallel assignment Some languages, like Ruby, Julia or Python support parallel assignments, which simplifies the notation for swapping two variables: a, b = b, a. This is shorthand for an operation involving an intermediate data structure: in Python and Julia, a tuple; in Ruby, an array. JavaScript 6+ supports destructuring operators which do the same thing: [a, b] = [b, a];.

Function swap Here, two globally scoped variables are passed by value through a function, eliminating the need for a temporary storage variable.

Facilitation of swapping in modern computers

Dedicated instructions Because of the many applications of swapping data in computers, most processors now provide the ability to swap variables directly through built-in instructions. x86 processors, for example, include an XCHG instruction to swap two registers directly without requiring that a third temporary register is used. A compare-and-swap instruction is even provided in some processor architectures, which compares and conditionally swaps two registers. This is used to support mutual exclusion techniques. XCHG may not be as efficient as it seems. For example, in x86 processors, XCHG will implicitly lock access to any operands in memory to ensure the operation is atomic, and so may not be efficient when swapping memory. Such locking is important when it is used to implement thread-safe synchronization, as in mutexes. However, an XCHG is usually the fastest way to swap two machine-size words residing in registers. Register renaming may also be used to swap registers efficiently.

Parallel execution With the advent of instruction pipelining in modern computers and multi-core processors facilitating parallel computing, two or more operations can be performed at once. This can speed up the swap using temporary variables and give it an edge over other algorithms. For example, the XOR swap algorithm requires sequential execution of three instructions. However, using two temporary registers, two processors executing in parallel can swap two variables in two clock cycles:

Step 1 Processor 1: temp_1 := X Processor 2: temp_2 := Y

Step 2 Processor 1: X := temp_2 Processor 2: Y := temp_1

More temporary registers are used, and four instructions are needed instead of three. In any case, in practice this could not be implemented in separate processors, as it violates Bernstein's conditions for parallel computing. It would be infeasible to keep the processors sufficiently in sync with one another for this swap to have any significant advantage over traditional versions. However, it can be used to optimize swapping for a single processor with multiple load/store units.

References

Illustrations

Swap (computer programming): swap means to exchange the value of two variables.
swap means to exchange the value of two variables.

Worked examples

Example 1 — a first encounter with Swap (computer programming)

Start with the simplest possible case. Write down what Swap (computer programming) claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Swap (computer programming) before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Swap (computer programming) ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Swap (computer programming)

In research
Swap (computer programming) appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Swap (computer programming) in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Swap (computer programming) is common in secondary-school and first-year university syllabi. It links to neighbouring topics Programming idioms, so understanding it makes those chapters shorter.
In everyday life
Look for Swap (computer programming) outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Swap (computer programming)” →

How to study Swap (computer programming) in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Swap (computer programming) means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Swap (computer programming) out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Swap (computer programming) in simple terms?

In computer programming, the act of swapping two variables mutually exchanges their values. Usually, this is done with the data in memory.

Why does Swap (computer programming) matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Swap (computer programming)?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Swap (computer programming).

Tags

  • Programming idioms

Keep exploring