FACTOID # 53: If you thought Antarctica was inhospitable, think again - its land area is only ninety-eight percent ice. Reassuringly, the other 2% is categorised as "barren rock".
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

FACTS & STATISTICS    Simple view

  1. Select countries to view: (hold down Control key and click to select several)

     

     

    Compare:

     

     

  1. Select fact or statistic: (* = graphable)

     

     

     

  2. (OPTIONAL) Compare to statistic: (both need to be graphable)

     

     

     

  3. View result as:

     

       
(OR) SEARCH ALL encyclopedia, stats & forums:   

Encyclopedia > Swap (computer science)

In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables. Usually, this is done with the data in memory. For example, in a program, two variables may be defined thus (in pseudocode): Wikipedia does not have an article with this exact name. ... It has been suggested that this article or section be merged with swap (computer science). ... Computer programming (often shortened to programming or coding) is the process of writing, testing, and maintaining the source code of computer programs. ... In computer science and mathematics, a variable (IPA pronunciation: ) (sometimes called a pronumeral) is a symbolic representation denoting a quantity or expression. ... This article or section does not adequately cite its references or sources. ... A computer program is a collection of instructions that describe a task, or set of tasks, to be carried out by a computer. ... Pseudocode (derived from pseudo and code) is a compact and informal high-level description of a computer programming algorithm that uses the structural conventions of programming languages, but omits detailed subroutines, variable declarations or language-specific syntax. ...

 data_item x := 1 data_item y := 0 

To swap them one might do

 swap (x, y); 

(In many programming languages where the swap function is built-in; in C++, overloads are provided allowing std::swap to swap some large structures in O(1) time.) After swap() is performed, x will contain the value 0 and y will contain 1; their values have been exchanged. Of course, this operation may be generalized to other types of values, such as strings, aggregated data types and possibly entire containers. A programming language is an artificial language that can be used to control the behavior of a machine, particularly a computer. ... In computer science, a subroutine (function, method, procedure, or subprogram) is a portion of code within a larger program, which performs a specific task and is relatively independent of the remaining code. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose, high-level programming language with low-level facilities. ... In computer science, polymorphism is the idea of allowing the same code to be used with different types, resulting in more general and abstract implementations. ... In computer programming and some branches of mathematics, strings are sequences of various simple objects. ... A data type is a constraint placed upon the interpretation of data in a type system in computer programming. ... A container is a type of data structure. ...

Contents

Swap methods

Swapping data is a very important component of numerous algorithms. For example, many of the sorting algorithms, especially comparison sorts, utilize swaps to change the positions of data. In mathematics, computing, linguistics, and related disciplines, an algorithm is a finite set of well-defined instructions for accomplishing some task which, given an initial state, will terminate in a defined end-state. ... In computer science and mathematics, a sorting algorithm is an algorithm that puts elements of a list in a certain order. ... A comparison sort is a particular type of sorting algorithm; a number of well-known algorithms are comparison sorts. ...


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, eg. in an array, may even need to copy the data manually. Object-oriented programming (OOP) is a programming paradigm that uses objects to design applications and computer programs. ... C++ (pronounced see plus plus, IPA: ) is a general-purpose, high-level programming language with low-level facilities. ... In object-oriented programming, a class is a programming language construct that is used to group related instance variables and methods. ... In object-oriented programming, a constructor (sometimes shorted to ctor) in a class is a special block of statements called when an object is created, either when it is declared (statically constructed on the stack, possible in C++ but not in Java and other object-oriented languages) or dynamically constructed... In object-oriented programming, a destructor is a method which is automatically invoked when the object is destroyed. ... In computer science, the object lifetime (or life cycle) of an object in object-oriented programming is the time between an objects creation (also known as instantiation or construction) till the object is no longer used, and is destructed or freed. ... This article or section does not cite its references or sources. ...


XOR swap

Main article: XOR swap algorithm

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. It has been suggested that this article or section be merged with swap (computer science). ... In computer programming, a bitwise operation operates on one or two bit patterns or binary numerals at the level of their individual bits. ... It has been suggested that this article or section be merged with swap (computer science). ... The integers are commonly denoted by the above symbol. ... A sequence of bits. ...


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 has been suggested that this article or section be merged with swap (computer science). ...

  • 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.

A container is a type of data structure. ... The term arithmetic overflow or simply overflow has the following meanings. ...

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/C++. For example, the STL specializes its built-in swap function to exchange containers efficiently this way. [1] A container is a type of data structure. ... In computer science, dynamic memory allocation is the allocation of memory storage for use in a computer program during the runtime of that program. ... In computer science, a pointer is a programming language datatype whose value refers directly to (points to) another value stored elsewhere in the computer memory using its address. ... Wikibooks has a book on the topic of C Programming The C programming language (often, just C) is a general-purpose, procedural, imperative computer programming language developed in the early 1970s by Dennis Ritchie for use on the Unix operating system. ... The Standard Template Library (STL) is a software library included in the C++ Standard Library. ... Generic programming is a style of computer programming where algorithms are written in an extended grammar and are made adaptable by specifying variable parts that are then somehow instantiated later by the compiler with respect to the base grammar. ...


As pointer variables are usually of a fixed size (eg. most desktop computers have pointers 32 bits long), and they are numeric, they can be swapped quickly using XOR swap. This article is about the unit of information. ...


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 CMPXCHG instruction, which compares and conditionally swaps two registers, is even provided in some processor architectures. Die of an Intel 80486DX2 microprocessor (actual size: 12×6. ... An Intel Pentium 4 chip; early Northwood build x86 or 80x86 is the generic name of a microprocessor architecture, first developed and manufactured by Intel. ... In computer architecture, a processor register is a small amount of very fast computer memory used to speed the execution of computer programs by providing quick access to commonly used values—typically, the values being in the midst of a calculation at a given point in time. ...


XCHG may not be as efficient as one may think. For example, in x86 processors, XCHG will implicitly lock access to any operands in memory to keep the operation atomic, and so may not be efficient when swapping memory. However, an XCHG is usually the fastest way to swap two machine-size words residing in registers. An Intel Pentium 4 chip; early Northwood build x86 or 80x86 is the generic name of a microprocessor architecture, first developed and manufactured by Intel. ... Random access memory (usually known by its acronym, RAM) is a type of data storage used in computers. ... In computer science, an atomic operation is an operation during which a processor can simultaneously read a location and write it in the same bus operation. ... In computer architecture, a processor register is a small amount of very fast computer memory used to speed the execution of computer programs by providing quick access to commonly used values—typically, the values being in the midst of a calculation at a given point in time. ...


Register renaming may also be used to swap registers efficiently. In computer engineering, register renaming refers to a technique used to avoid unnecessary serialization of program operations imposed by the reuse of registers by those operations. ...


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 lowly temporary-variable swap algorithm 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: Basic five-stage pipeline in a RISC machine (IF = Instruction Fetch, ID = Instruction Decode, EX = Execute, MEM = Memory access, WB = Register write back) An instruction pipeline is a technique used in the design of computers and other digital electronic devices to increase their performance. ... This article or section does not adequately cite its references or sources. ... Parallel computing is the simultaneous execution of the same task (split up and specially adapted) on multiple processors in order to obtain results faster. ... It has been suggested that this article or section be merged with swap (computer science). ...

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

This uses fewer instructions; but other temporary registers may be in use, and four instructions are needed instead of three. In any case, in practice this could not be implemented in separate processors, as 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.



 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments
Please enter the 5-letter protection code

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.