原地swap(inplace_swap)

inplace_swap algorithm based on exclusive-or (^)

void inplace_swap(int *x, int *y) {
	*y = *x ^ *y;
	*x = *x ^ *y;
	*y = *x ^ *y;
}

原理(展开为二进制计算异或即可):
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0


reverse_array algorithm based on inplace_swap

void reverse_array(int a[], int cnt) {
	for (int left=0, right=cnt-1; left < right; ++left, --right)
	inplace_swap(&a[left], &a[right]);
}

int main() {
	int a[] = {1,2,3,4,5,};
	reverse_array(a, 5);
	for (int i=0; i<5; ++i)
		printf("%d", a[i]);
	return 0;
}

note that:
条件是left < right,如果改为<=,则对于奇数个序列(e.g., {1,2,3,4,5})而言会得到5,4,0,2,1,原因如下:
当l=r=2时,在同一个地址执行*y = *x ^ *y;y=0(即0110 ^ 0110 = 0000),也即该地址的值为0,此后再进行*x = *x ^ *y;的时候并不是在做0110 ^ 0000 = 0110而是0000 ^ 0000 = 0000,因为此时x和y指向同一个地址;

你可能感兴趣的:(算法,数据结构)