In
computer programming
Computer programming is the process of performing a particular computation (or more generally, accomplishing a specific computing result), usually by designing and building an executable computer program. Programming involves tasks such as anal ...
, the act of swapping two
variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in
memory
Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembered ...
. For example, in a
program, two variables may be defined thus (in
pseudocode
In computer science, pseudocode is a plain language description of the steps in an algorithm or another system. Pseudocode often uses structural conventions of a normal programming language, but is intended for human reading rather than machine re ...
):
data_item x := 1
data_item y := 0
swap (x, y);
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 type
In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
s.
Comparison sort
A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation (often a "less than or equal to" operator or a three-way comparison) that determines which of two elements should oc ...
s use swaps to change the positions of data.
In many
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
s 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
In computer programming, a temporary variable is a variable with short lifetime, usually to hold data that will soon be discarded, or before it can be placed at a more permanent memory location. Because it is short-lived, it is usually declared as ...
:
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
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
languages such as
C++ may involve one call to the
class constructor
Constructor may refer to:
Science and technology
* Constructor (object-oriented programming), object-organizing method
* Constructors (Formula One), person or group who builds the chassis of a car in auto racing, especially Formula One
* Construc ...
and
destructor for the temporary variable, and three calls to the
copy constructor
In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set requir ...
. 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
An array is a systematic arrangement of similar objects, usually in rows and columns.
Things called an array include:
{{TOC right
Music
* In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
, 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
integer
An integer is the number zero (), a positive natural number (, , , etc.) or a negative integer with a minus sign ( −1, −2, −3, etc.). The negative numbers are the additive inverses of the corresponding positive numbers. In the language ...
s. 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
A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping.
Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
.
* When swapping variables of a fixed size,
arithmetic overflow
Arithmetic () is an elementary part of mathematics that consists of the study of the properties of the traditional operations on numbers—addition, subtraction, multiplication, division, exponentiation, and extraction of roots. In the 19th ...
becomes an issue.
* It does not work generally for floating-point values, because
floating-point arithmetic
In computing, floating-point arithmetic (FP) is arithmetic that represents real numbers approximately, using an integer with a fixed precision, called the significand, scaled by an integer exponent of a fixed base. For example, 12.345 can b ...
is
non-associative.
Swapping containers
Containers
A container is any receptacle or enclosure for holding a product used in storage, packaging, and transportation, including shipping.
Things kept inside of a container are protected on several sides by being inside of its structure. The term ...
which allocate memory from the
heap
Heap or HEAP may refer to:
Computing and mathematics
* Heap (data structure), a data structure commonly used to implement a priority queue
* Heap (mathematics), a generalization of a group
* Heap (programming) (or free store), an area of memory f ...
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
Standard Template Library
The Standard Template Library (STL) is a software library originally designed by Alexander Stepanov for the C++ programming language that influenced many parts of the C++ Standard Library. It provides four components called ''algorithms'', ''co ...
overloads its built-in swap 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
bit
The bit is the most basic unit of information in computing and digital communications. The name is a portmanteau of binary digit. The bit represents a logical state with one of two possible values. These values are most commonly represented a ...
s long), and they are numeric, they can be swapped quickly using
XOR swap.
Parallel assignment
Some languages, like
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
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, a tuple; in Ruby, an array.
Javascript 6+ supports destructuring operators which do the same thing:
, b
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline o ...
= , a
The comma is a punctuation mark that appears in several variants in different languages. It has the same shape as an apostrophe or single closing quotation mark () in many typefaces, but it differs from them in being placed on the baseline ...
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
In computer science, compare-and-swap (CAS) is an atomic instruction used in multithreading to achieve synchronization. It compares the contents of a memory location with a given value and, only if they are the same, modifies the contents of th ...
instruction is even provided in some processor architectures, which compares and conditionally swaps two registers. This is used to support
mutual exclusion
In computer science, mutual exclusion is a property of concurrency control, which is instituted for the purpose of preventing race conditions. It is the requirement that one thread of execution never enters a critical section while a concurrent ...
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
Memory is the faculty of the mind by which data or information is encoded, stored, and retrieved when needed. It is the retention of information over time for the purpose of influencing future action. If past events could not be remembered ...
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 computer engineering, instruction pipelining or ILP is a technique for implementing instruction-level parallelism within a single processor. Pipelining attempts to keep every part of the processor busy with some instruction by dividing inco ...
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
{{DEFAULTSORT:Swap (Computer Science)
Programming idioms