Exchange two variables. our usual practice is (especially in the learning stage): define a new variable and use it to complete the exchange. 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 is easy for programmers to communicate with each other. Generally, this algorithm should be used to exchange variable values.
Exchange two variables. our usual practice is (especially in the learning stage): 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 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.
Do not use the third variable to swap two variables.
Method 1:
';echo $b.'
';?>
The second method is to use bitwise operators:
';echo $b.'
';$a="a";$b="b";$a=$a^$b;$b=$a^$b;$a=$a^$b;echo $a.'
';echo $b.'
';?>
The third type is not very good:
';echo $b.'
';?>
The above three 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.
This article is available at http://www.nowamagic.net/librarys/veda/detail/1008.