Swap the value of two variables without using the four kinds of the third variable

Source: Internet
Author: User
Tags arithmetic

Turn from: http://blog.163.com/jian_xiong/blog/static/19193236320130604848997/

Usually our approach is (especially during the learning phase): Define a new variable and use it to complete the 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, especially suitable for beginners to understand the characteristics of computer programs, is the classical application of assignment statements. In the actual software development, this algorithm is simple and clear, does not produce ambiguity, easy to communicate between programmers, in general, when the problem of Exchange variable value, should adopt this algorithm (hereinafter referred to as the standard algorithm).

The biggest disadvantage of the above algorithm is that it requires a temporary variable. So you can exchange without the help of a temporary variable. The answer is yes. Here we can use three kinds of algorithms to achieve: 1 arithmetic operation, 2 pointer address operation, 3 bit operation, 4 stack implementation.
1) Arithmetic operation
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
Its principle is: A, b as a point on the axis, around the distance between two points to calculate.
Specific process: The first sentence "a=b-a" to find out AB two points of distance, and keep it in a, the second sentence "b=b-a" to find the distance from the origin (b to the origin of the distance from AB two points), and save it in B; the third sentence "A=b+a" Find the distance from B to the origin (A to the sum of the distance from the AB two point) and save it in a. Complete the exchange.
This algorithm has three more computational procedures than the standard algorithm, but it does not use temporary variables. The disadvantage of (hereinafter called arithmetic) is that it can only be used for numeric types, strings, and so on. A+b may overflow (beyond the scope of int), overflow is relative, + overflow,-back not good, so overflow does not overflow does not matter, is not safe.

2) Pointer address operation
Because the operation of the address is actually an integer operation, for example: two addresses subtract an integer representing the number of bytes of two variables stored in memory; The address and an integer, "a+10", represent the address of the 10 Class A data units with a base address in a. Therefore, in theory, the exchange of addresses can be accomplished by a similar operation to the arithmetic algorithm, so as to achieve the purpose of exchanging variables. That
int *a,*b; Assume
*a=new Int (10);
*b=new Int (20); &a=0x00001000h,&b=0x00001200h
A= (int*) (B-A); &a=0x00000200h,&b=0x00001200h
B= (int*) (B-A); &a=0x00000200h,&b=0x00001000h
A= (int*) (B+int (a)); &a=0x00001200h,&b=0x00001000h
The address of A and B has really been exchanged through the above operation, and a points to the original B-point value, and B to the value pointed to by the previous point. The code above can be compiled, but the execution results are incredible. why.
First, you must understand that the operating system divides memory into several areas: system code/Data area, application code/data area, stack area, global data area, and so on. When compiling the source program, constants, global variables, and so on are put into the global data area, and local variables and dynamic variables are put into the stack area. Thus, when the algorithm executes to "a= (int*)" (b-a), the value of a is not 0x00000200h, but the base address of the memory area where the variable a resides, the actual result is 0x008f0200h, where the 0x008f is the base address, and 0200 is the displacement of a in the memory area. It is automatically added by the compiler. Therefore, the subsequent address calculation is incorrect, so that a,b points to the other internal deposit in the region. Again, address operations can not be negative, that is, when a's address is greater than the address of B, b-a<0, the system automatically uses the form of complement to express the negative displacement, resulting in errors, resulting in the same result as before.
Is there any way to solve it. Of course. The following are the improved algorithms:
if (a<b)
{
A= (int*) (B-A);
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 with the operation "Int (a) &0x0000ffff", because the address of high 16 bits for the segment address, the latter 16 digits for the displacement address, it and 0x0000ffff after the operation, segment address is blocked, only the displacement address. This will match the original algorithm and get the correct result.
This algorithm also does not use the third variable to complete the exchange of value, compared with the arithmetic algorithm it is difficult to understand, but it has its advantages that in the exchange of large data types, it is faster than the arithmetic algorithm. The value of the variable is not moved in memory because it exchanges the time address. (hereinafter referred to as the address algorithm)

3) Bit 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;
This algorithm can be implemented by the characteristics of XOR or operation, through XOR or operation can make some bits in the data flip, the other bit unchanged.   This means that any number of any given value is continuously different or two times, and the value is unchanged. 4) Stack implementation. Not much explained, the stack and correlation function definitions are omitted.
int exchange (int x,int y)
{
Stack S;
Push (S,X);
Push (S,y);
X=pop (S);
Y=pop (S);
}
All of the above algorithms realize the exchange of two variable values without other variables. Compared with arithmetic algorithms and bit algorithms, the computation of address algorithm is more complicated, but it can easily realize the exchange of large type (such as custom class or structure), while the first two can only be exchanged for shaping data (theoretically overloaded "^"). operator, you can also implement an interchange of any structure.
The introduction of these three algorithms is not to be applied to practice, but to explore technology, show the charm of programming. It can be seen that the mathematics of the small skills in the design of a considerable influence, the use of appropriate will have unexpected magical effect. From the actual software development, the standard algorithm is undoubtedly the best, can solve any type of exchange problem. Data reference: Http://www.blogjava.net/caizh2009/archive/2009/12/02/304514.html http://hi.baidu.com/zealot886/ite m/b6689c0eac8b0e9ca2df4372


From: Why XOR can be exchanged for two integers without resorting to the 3rd temporary variable

The usual process of exchanging two variables a,b is

int temp;

Temp=a

a=b;

b=temp;

need to use the 3rd temporary variable above temp.


using the following method, for a given two-integer a,b, the following XOR can be exchanged for a,b without the help of a 3rd temporary variable:

A = a ^ b;
b = a ^ b;
A = a ^ b;

This exchange of two variables without recourse to the 3rd temporary variable process, its implementation is mainly based on the following properties of the xor :

1. Any one of the variable X and its own to do or operation, the result is 0, namely X^x=0

2. any one variable X and 0 to be different or operation, the result is unchanged, namely X^0=x

3. XOR or operation has the binding, namely a^b^c= (a^b) ^c=a^ (b^c)

4. XOR or operation is interchangeable, namely A^b=b^a


Analysis:

The first step: a = a ^ b;

The result of a variable after completion is a ^ b


Step Two: b = a ^ b;

A value of a ^ B is saved by a on the right of the assignment number, then a ^ B is substituted for a on the right side of the assignment .

Get (a ^ b) ^ B=a ^ (b ^ b) =a ^0=a,

that is, after the second operation, the value in B is a, that is, b=a, and A is changed to B .


Step Three: a = a ^ b;

at this point, the right of the assignment is still the value of a ^ B, unchanged, and the B on the right of the assignment number is already a,

Replace the a,b on the right side of the assignment number,

that is, the right of the assignment, a ^ b= (a ^ b) ^ A=a ^ b^ a=a ^ a^ b=0^ b=b, which assigns a value to a, that is, a=b

that is, after the third operation, the value of a is B, that is, a=b, b into a

This completes the exchange of two variable a,b without recourse to the 3rd temporary variable procedure, as in the three steps above.

This process is equivalent to the following procedure:

a=a+b

B=a-b;

A=a-b;

The premise is that the value of a+b cannot overflow.

The test procedure is as follows:

int Main ()
{
int a = 4, b = 5;
printf ("a=%d b=%d\n", A, b);
A = a ^ b;
b = a ^ b;
A = a ^ b;
printf ("a=%d b=%d\n", A, b);
}

Run Result:
[Root@test cs]#./a.out
A=4 b=5
A=5 b=4
[Note: This method does not apply when a and B are equal]

--The end of this article --

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.