Swap (computer science)
As a triangle exchange is referred to in programming a method for exchanging the values of two variables. In this case, an auxiliary variable is used to latch the value of the variable, which is first overwritten. A typical application of the triangle exchange is, for example, in some sorting algorithms such as bubble-sort. The general principle is as follows:
If it is linkable binary values with the values of the two variables to be replaced, you can barter through repeated XOR operations ( taking advantage of the law (A xor B) xor B = A) also realize entirely without auxiliary variable:
Two other possibilities for exchanging ordinates without auxiliary variable is by repeated addition and subtraction:
Or:
This only works for integers, otherwise it could lead to extinctions in floating point numbers. Strictly speaking, there is no longer a triangle exchange.
In some languages (including C ) and when the data type supports binary XOR operation, does the statement
In which
Stands.
For numeric values, also works:
Some languages , such as Ruby or Python that support multiple assignments, creating a triangle exchange is unnecessary:
- Programming