Classical algorithm learning-exchanging Two integer data
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.