The two-digit value that is often used by the interchange algorithm

Source: Internet
Author: User

Exchange two variable values, old topic, the following summarizes the various methods are.

For convenience, define two variables first.

int a = 1;int B = 2;

Exchange variable values with a temporary variable of 1
int tmp;tmp = a;//TMP = 1a = b;//A = 2b = tmp;//B = 1


2 Exchange Address

int *p;p = &a;//tmp->1 a = &b;//a->2b = p;//b->1


The second does not use the third variable 1 plus subtraction
A = a + b//a = 3b = a-b//b = 1a = a-b//A = 2

2 Multiplication method
A = A * b//2b =/A//2a = A/b//1


3 XOR Law
a:0000 0001//b:0000 0010a = a ^ b//a:0000 0011b = a ^ b//b:0000 0001a = a ^ b//a:0000 0010


For each of the above methods, the intermediate variable requires additional memory space.
The addition and subtraction and multiplication methods may appear to be out of bounds, or divide by 0, and only apply to numerical operations;

The better one is the last, low-memory operation (/* All kinds of data types */, This place is my mistake, XOR can only be used for integral type, thanks to Xiacanni 's reminders ).



Copyright notice: This article Bo Master original article. Blog, not reproduced without consent.

The two-digit value that is often used by the interchange algorithm

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.