Exchange the values of two shaping variables without using any intermediate variables

Source: Internet
Author: User

Today, when doing a problem, suddenly appeared a problem, is not the use of intermediate variables, the value of two shaping variables to swap, began a bit of a Meng, how to change? Later or with two variables constantly do plus and minus transformation, almost more than 10 minutes, and finally come up with a method, a moment, I found a bit of information on the Internet, said that there are four ways, I looked at a bit, by the way to learn.

In our beginner stage, we usually define a new variable and use it to complete the exchange.

For example:
int A, B;
A=1; b=2;
int t;
T=a; A=b; d=2;
This algorithm is easy to understand, for beginners, is generally used "empty bottle back and forth" to help understand, and is the classic application of assignment statements, in the beginner sort often used. Online said in the actual software development, this algorithm is also simple and clear, will not produce ambiguity, easy communication between programmers, in general, encountered the Exchange variable value of the problem, should adopt this algorithm.

However, there are several other algorithms that do not require intermediate variables to achieve this function.

First of all, I figured out, online is the function of arithmetic operations:

1. Arithmetic operations

int a =1, b = 2;
A=b-a; A=1
B=b-a; B=1
a=b+a;//a=2

I've come up with this algorithm called arithmetic arithmetic, but there's an explanation on the Internet:

Its principle is: The A, b as a point on the axis, around the distance between two points to calculate.
The specific process: The first sentence "a=b-a" to find the distance ab two points, and save it in a, the second sentence "b=b-a" to find a to the origin of the distance (b to the origin of the distance and the difference between AB two points), and save it in B; the third sentence "A=b+a" Find the distance from the B to the origin (the sum of the distance from a to the origin of the AB two point) and save it in a. Complete the interchange.
compared with the standard algorithm, this algorithm has more than three computational processes, but no temporary variables. (hereinafter referred to as arithmetic algorithms) disadvantage: is only used for numeric types, such as the string can not be. A+b is possible overflow (beyond the range of int), overflow is relative, + overflow,-come back not good, so overflow does not overflow does not matter, is not safe.

2. Bit arithmetic

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 the XOR operation is determined by the XOR operation can make some bits in the data flip, the other bits unchanged. This means that any number is continuously different or two times with any given value, and the value does not change.

3. 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 variables without the help of other variables, compared with the arithmetic algorithm and bit algorithm computation, the algorithm is more complex, but it can easily realize the exchange of large type (such as custom class or structure), and the first two types can only be exchanged for shaping data (theoretically overloaded "^" operator, you can also implement any structure of the interchange).
The introduction of these three algorithms is not to apply to practice, but to explore the technology, show the charm of program design. It can be seen that the small skills in mathematics have a considerable impact on program design, 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.

The above three kinds can be implemented in Java, but the following one seems to be no longer implemented in Java, it involves pointers in C language

3 Pointer address operation

because the operation of the address is actually an integer operation, such as: two address subtraction to get an integer, which indicates how many bytes of two variables are stored in memory, and the address and an integer added as "A+10" represents the address of the 10 Class A data units with a base address after a. Therefore, it is theoretically possible to accomplish the exchange of the address by an operation similar to the arithmetic algorithm to achieve the purpose of exchanging variables. namely:
int *a,*b;//hypothesis
*a=new Int (ten);
*b=new Int (//&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
through the above operation A, B's address really has completed the exchange, and a point to the original B point to the value, B point to the original a point value? The code above can be compiled, but the execution results are incredible! Why?
first, it must be understood that the operating system divides the memory into several areas: the system code/data area, the application code/data area, the stack area, the global data area, and so on. When compiling the source program, constants, global variables, etc. are put into the global data area, and local variables and dynamic variables are placed in the stack area. When the algorithm executes to "a= (int*)" (b-a), the value of a is not 0x00000200h, but to add the base address of the memory area where the variable A is located, the actual result is: 0x008f0200h, where 0x008f is the base address, and 0200 is the displacement of a in that 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 cells in the area. Again, the address operation can not appear negative, that is, when the address of a is greater than the address of B, b-a<0, the system automatically uses the form of complement to indicate negative displacement, resulting in errors, resulting in the same results as before.
is there a 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 and operation "Int (a) &0x0000ffff", because the address of the high 16 bits is the segment address, the latter 16 is the displacement address, it and 0x0000ffff after the operation, the segment address is masked, only the displacement address is reserved. This matches the original algorithm so that the correct results are obtained.
This algorithm also does not use the third variable to complete the value of the exchange, and arithmetic algorithm compared it is not good to understand, but it has its advantage that when exchanging a large data type, it executes faster than the arithmetic algorithm. Because it swaps the time address, the variable value is not moved in memory. (hereinafter referred to as the address algorithm)

This is what we now know about the conversion between the values of two shaping variables without the use of a third variable.

                                         ,         &NB Sp                          ,         &NB Sp                          ,         &NB Sp                    -------------------------------------------------- ------------------------------

Boldface is a special reference for Kangkermit Bar

Exchange the values of two shaping variables without using any intermediate variables

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