Classical algorithm Learning--exchanging two integer data
The exchange of two numbers is often used in programming, of course, we can do it in a very common way, but also can be a variety of strange ways to do. There are three more conventional ways to do this, and it's too weird for individuals to feel that it's not necessary. Instance code upload to: https://github.com/chenyufeng1991/SwapFunction
(1) Using pointers
The implementation is as follows:
main.c// swapfunc//// Created by Chenyufeng on 16/2/3.//copyright©2016 year 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", b); SWAP01 (&a, &b); printf ("After exchange: a =%d,b =%d\n", b); return 0;} The most general interchange; 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 year 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", b); SWAP02 (&a, &b); printf ("After exchange: a =%d,b =%d\n", b); return 0;} Without a third number; void swap02 (int *a,int *b) { *a = *a + *b; *b = *a-*b; *a = *a-*b;}
(3) different or
main.c// swapfunc//// Created by Chenyufeng on 16/2/3.//copyright©2016 year chenyufengweb. All rights reserved.//#include
/** * because I use the C language here, I can't use references. References can be used in C + +. Referenced function definition: void swap04 (int &a,int &b) {...} */void swap03 (int *a,int *b); int main (int argc, const char * argv[]) { C8/>int a = 1; int b = 2; printf ("before exchange: A =%d,b =%d\n", b); SWAP03 (&a, &b); printf ("After exchange: a =%d,b =%d\n", b); return 0;} XOR, calculated using bits, void swap03 (int *a,int *b) { *a = *a ^ *b; *b = *b ^ *a; *a = *a ^ *b;}
The above three implementations should be able to be written in closed eyes, but also fully understood.
http://www.bkjia.com/PHPjc/1121831.html www.bkjia.com true http://www.bkjia.com/PHPjc/1121831.html techarticle Classical Algorithm Learning-Exchange two integer data exchange two numbers are often used in programming, of course, we can use a very common way to achieve, can also be a variety of strange side ...