Classical algorithm learning-exchange two integer data types. Classical algorithm learning-switching two integer data exchanges two numbers is often used in programming, of course, we can use a very common way to achieve, you can also learn from a variety of strange classical algorithms-exchange two integer data types.
The exchange of two numbers is often used in programming. of course, we can implement them in a common way or in a variety of odd ways. Here we use three more conventional methods. the odd method is not necessary. Instance code uploaded to: https://github.com/chenyufeng1991/SwapFunction
(1) use pointer
The implementation is as follows:
/// Main. c // SwapFunc // Created by chenyufeng on 16/2/3. // Copyright©2016 chenyufengweb. All rights reserved. // # include
Void swap01 (int * a, int * B); int main (int argc, const char * argv []) {int a = 1; int B = 2; printf ("before exchange: a = % d, B = % d \ n", a, B); swap01 (& a, & B); printf ("after exchange: a = % d, B = % d \ n ", a, B); return 0;} // The most common exchange; void swap01 (int * a, int * B) {int temp; temp = * a; * a = * B; * B = temp ;}
(2) do not borrow the third number
/// Main. c // SwapFunc // Created by chenyufeng on 16/2/3. // Copyright©2016 chenyufengweb. All rights reserved. // # include
Void swap02 (int * a, int * B); int main (int argc, const char * argv []) {int a = 1; int B = 2; printf ("before exchange: a = % d, B = % d \ n", a, B); swap02 (& a, & B); printf ("after exchange: a = % d, B = % d \ n ", a, B); return 0;} // do not use the third number; void swap02 (int * a, int * B) {* a = * a + * B; * B = * a-* B; * a = * a-* B ;}
(3) exclusive or
/// Main. c // SwapFunc // Created by chenyufeng on 16/2/3. // Copyright©2016 chenyufengweb. All rights reserved. // # include
/*** I use C language here, so reference cannot be used. References can be used in C ++. Reference function definition: void swap04 (int & a, int & B ){...} */void swap03 (int * a, int * B); int main (int argc, const char * argv []) {int a = 1; int B = 2; printf ("before exchange: a = % d, B = % d \ n", a, B); swap03 (& a, & B); printf ("after exchange: a = % d, B = % d \ n ", a, B); return 0;} // returns or, using binary bits for computation; void swap03 (int *, int * B) {* a = * a ^ * B; * B = * B ^ * a; * a = * a ^ * B ;}
The above three implementations should be written with your eyes closed and fully understandable.
Swap swap two numbers are often used in programming, of course we can use a very common way to achieve, but also a variety of strange ways...