(Java Edition) algorithm - variable values and switching arrays are two basic types of data elements exchange position

Switching element positions (positioning calculation method and the auxiliary space method) array

In the algorithm, often encounter two exchange positions in the array elements of problems or issues variable values ​​exchanged two basic types of data

Auxiliary space method

Exchanging two basic data types of variables
int a=1,b=2;
int tmp=a;
a=b;
b=temp;   
//此时a=2,b=1
Exchange positions of elements in the array
public static void swap(int[] arr, int i, int j) {
	int tmp = arr[i];
	arr[i] = arr[j];
	arr[j] = tmp;
}

Bit computing method

Bit exclusive-OR operation (^)

Operational rule

Two numbers into binary, and then start from relatively high, if compared with the same 0, 1 was not the same.
. For example: ^ 11 8
8 binary is converted into a binary 1000,11 1011. The high-order comparison is obtained is:. 0011 binary to decimal and then, is Integer.parseInt ( "0011", 2) = 3;

Exchanging two basic data types of variables
int f = 50;    //二进制 110010
int g = 60;    //二进制 111100
f = f^g;   //110010,111100——>001110
g = f^g;   //001110,111100——>110010  ——>50
f = f^g;   //001110,110010——>111100  ——>60
System.out.println(f+" "+g);//输出结果是:60 50
Exchange positions of elements in the array
public static void swap(int[] arr, int i, int j) {
	arr[i] = arr[i] ^ arr[j];
	arr[j] = arr[i] ^ arr[j];
	arr[i] = arr[i] ^ arr[j];
}

Both methods comparison

Using a bitwise XOR operation (^) auxiliary space saving, reducing spatial complexity

Published 14 original articles · won praise 7 · views 2892

Guess you like

Origin blog.csdn.net/qq_42937522/article/details/104501889