package com.demo.algorithm.sort;
public class NumberSwap {
/**
* 通过中间值进行交换
* @param a
* @param b
*/
public static void swap1(int a,int b){
int tmp=a;
a=b;
b=tmp;
display(a, b);
}
/**
* 两数求和然后相减的方式进行交换,x、y过大有可能超出int的最大值
* @param a
* @param b
*/
public static void swap2(int a,int b){
a=a+b;
b=a-b;
a=a-b;
display(a, b);
}
/**
* 原理:一个数异或同一个数两次,结果还是那个数
* @param a
* @param b
*/
public static void swap3(int a,int b){
a=a^b;
b=a^b;//a^b^b
a=a^b;//a^b^a^b^b
display(a, b);
}
public static void display(int a,int b){
System.out.println("a="+a+",b="+b);
}
public static void main(String[] args) {
swap1(5, 8);
swap2(5, 8);
swap3(5, 8);
}
}
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn