《深刻理解计算机系统》中介绍了一种交换元素值的位操做方法,很是巧妙,而且高效,在这里贴出代码。数组
void inplace_swap(int *x, int *y)函数
{spa
*y=*x^*y;it
*x=*x^*y;ast
*y=*x^*y;方法
}计算机
这个函数能够实现x和y指向的元素的值的交换,^表明异或操做。证实能够分x,y各位元素为00,01,10,11四种状况讨论。因为是位操做,因此比通常的交换数值的方法高效。一个应用是数组元素反序。代码也贴在这里,仅供参考:深入理解计算机系统
void reverse_array(int a[],int cnt)void
{printf
int first,last;
for(first=0,last=cnt-1;first<last;first++,last--)
inplace_swap(&a[first],&a[last]);
for(first=0;first<cnt;first++)
printf("%d ",a[first]);
}