用元素交换函数实现数组逆置很简单,如下面代码:(数组左右元素交换)
#include<iostream> #include<stdlib.h> using namespace std; void swap(int &a, int &b) { int tmp = a; a = b; b = tmp; } int main() { int a[5] = { 1, 2, 3, 4, 5 }; int lenth = sizeof(a) / sizeof(a[0]); int head = 0; int tail = lenth - 1; while (head <= tail) { swap(a[head], a[tail]); head++; tail--; } for (int i = 0; i < lenth; ++i) { cout << a[i] << endl; } system("pause"); }
有人会说,用异或操作实现交换函数效率更高,于是写下如下代码:
<span style="font-family:KaiTi_GB2312;">#include<iostream> #include<stdlib.h> using namespace std; void swap(int &a, int &b) { a = a ^ b; b = a ^ b; a = a ^ b; } int main() { int a[5] = { 1, 2, 3, 4, 5 }; int lenth = sizeof(a) / sizeof(a[0]); int head = 0; int tail = lenth - 1; while (head <= tail) { swap(a[head], a[tail]); head++; tail--; } for (int i = 0; i < lenth; ++i) { cout << a[i] << endl; } system("pause"); }</span>
一运行,结果大跌眼镜:0哪来的????
异或操作实现交换的机制: a ^ a = 0即同一个元素相异或之后为0
a = a ^ b;
b = a ^ b = a ^ b ^ b = a;
a = a ^ b = a ^ b ^ a = b;
经分析:原来如此,当head = tail = (lenth-1)/ 2时,二者指向同一个元素,即
a = b = 3(同一块内存)
a = a ^ b = 3 ^ 3 = 0(内存内容改变为0)---->>> a = b = 0;
b = a ^ b = 0 ^ 0 = 0
a = a ^ b = 0 ^ 0 = 0
所以执行之后变为了0
那么该怎样修改呢???
while (head < tail)//改变此处 { swap(a[head], a[tail]); head++; tail--; }
以后注意,把条件写成 while(head < tail)即同一个元素无需交换,即加快了执行效率,又可以避免上述问题!!
与其相关的一道面试题点击打开链接
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-06 16:00:49