Exchange the values of two variables without using the four methods of the third variable

Source: Internet
Author: User

Our practice is usually (especially in the learning phase): to define a new variable and use it for exchange. The Code is as follows: int A, B;
A = 10; B = 15;
Int T;
T = A; A = B; B = T;
This algorithm is easy to understand and is especially suitable for beginners to understand the characteristics of computer programs. It is a classic Application of Value assignment statements. In actual software development, this algorithm is simple and clear, and does not produce ambiguity. It facilitates communication between programmers. In general, you may encounter the problem of switching variable values, this algorithm should be used (hereinafter referred to as the standard algorithm ).

The biggest drawback of the above algorithm is that a temporary variable is needed. Can I exchange data without using temporary variables? The answer is yes! Here we can use three algorithms: 1) arithmetic operation; 2) pointer address operation; 3) bitwise operation; 4) stack implementation.
1) arithmetic operations
Int A, B;
A = 10; B = 12;
A = B-A; // A = 2; B = 12
B = B-A; // A = 2; B = 10
A = B + A; // A = 10; B = 10
The principle is to regard a and B as points on the number axis and calculate the distance between two points.
Specific process: in the first sentence "A = B-a", find the distance between the two points of AB and save it in; in the second sentence, B = B-A is used to determine the distance from a A to the origin (the distance from B to the origin), and save it in B; in the third sentence "A = B + A", find the distance from B to the origin (the sum of the distance between A and AB) and save it in. Complete the exchange.
Compared with the standard algorithm, this algorithm has three more computing processes, but does not use temporary variables. (Hereinafter referred to as an arithmetic algorithm) Disadvantage: it can only be used for numeric types, strings, and so on. A + B may overflow (beyond the int range). Overflow is relative. + overflow.-back is not good, so overflow does not affect the relationship, that is, it is not safe.

<br>
<br>
<br>
<br>
<br>
<br>
<br>
A = (int *) (B + int (a); // & A = 0x00001200 H, & B = 0x00001000 H
After the preceding operations, the addresses of A and B have already completed the exchange, and a points to the original B's value. Does B point to the original A's value? The above code can be compiled, but the execution results are incredible! Why?
First, you must understand that the operating system divides the memory into several areas: system code/Data zone, application code/Data zone, stack zone, global data zone, and so on. When compiling the source program, constants and global variables are all placed in the global data area, and local variables and dynamic variables are placed in the stack area. In this way, when the algorithm is executed to "A = (int *) (B-A)", the value of A is not 0x00000200 H, instead, add the base address of the memory zone where variable A is located. The actual result is 0x008f0200h, where 0x008f is the base address, and 0200 is the displacement of a in the memory zone. It is automatically added by the compiler. Therefore, subsequent address calculations are incorrect, so that a and B point to other memory units in the SWAp area. Again, there cannot be a negative number in the address operation, that is, when the address of A is greater than the address of B, B-A <0, the system automatically uses the complement form to represent the Negative displacement, this produces errors, resulting in the same results as the previous one.
Is there a solution? Of course! The following is an improved algorithm:
If (A <B)
{
A = (int *) (B-);
B = (int *) (B-(INT (a) & 0x0000ffff ));
A = (int *) (B + (INT (a) & 0x0000ffff ));
}
Else
{
B = (int *) (a-B );
A = (int *) (a-(INT (B) & 0x0000ffff ));
B = (int *) (a + (INT (B) & 0x0000ffff ));
}
The biggest improvement of the algorithm is to use the bitwise operation and the operation "int (a) & 0x0000ffff", because the top 16 bits in the address are segment addresses, and the last 16 bits are displacement addresses, after performing the operation with 0x0000ffff, the segment address is blocked and only the displacement address is reserved. In this way, the original algorithm is consistent to obtain the correct result.
This algorithm does not use the third variable to complete the value exchange. It is not easy to understand compared with the arithmetic algorithm, but it has the advantage that when switching a large data type, it performs faster than arithmetic algorithms. Because of the address it exchanges, the variable value is not moved in the memory. (Hereinafter referred to as address algorithm)

3) bitwise operation
Int A = 10, B = 12; // A = 1010 ^ B = 1100;
A = a ^ B; // A = 0110 ^ B = 1100;
B = a ^ B; // A = 0110 ^ B = 1010;
A = a ^ B; // A = 1100 = 12; B = 1010;
The implementation of this algorithm is determined by the characteristics of the exclusive or operation. Through the exclusive or operation, some bits in the data can be flipped while others remain unchanged. This means that any number and any given value are two consecutive times without changing the value. 4) stack implementation. The stack and related function definitions are omitted.
Int Exchange (int x, int y)
{
Stack S;
Push (S, X );
Push (S, y );
X = POP (s );
Y = POP (s );
}
The above algorithms both implement the exchange of two variable values without using other variables. In comparison, the calculation of arithmetic algorithms and bit algorithms is equivalent, and the calculation of address algorithms is more complex, but it is easy to implement the exchange of large types (such as custom classes or structures), while the first two can only exchange integer data (theoretically reload the "^" operator, or any structure can be exchanged ).
The introduction of these three algorithms is not to be applied to practice, but to explore technology and demonstrate the charm of program design. It can be seen that the tips in mathematics have a considerable influence on programming, and using them properly will have unexpected magical effects. From the perspective of actual software development, standard algorithms are undoubtedly the best and can solve any type of exchange problems. Http://www.blogjava.net/caizh2009/archive/2009/12/02/304514.html http://hi.baidu.com/zealot886/item/b6689c0eac8b0e9ca2df4372

Exchange the values of two variables without using the four methods of the third variable

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.