![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1
int
[] arrInt32
=
new
int
[] {
41
,
88
,
80
,
73
,
57
,
88
,
28
,
56
,
34
};
2 for ( int x = 0 ; x < 9 ; x ++ )
3 {
4
5 for ( int y = 0 ; y < 9 - 1 ; y ++ )
6 {
7 if (arrInt32[y] > arrInt32[y + 1 ])
8 {
9 arrInt32[y] ^= arrInt32[y + 1 ];
10 arrInt32[y + 1 ] ^= arrInt32[y];
11 arrInt32[y] ^= arrInt32[y + 1 ];
12 }
13
14 }
15
16 }
17 for ( int i = 9 ; i > 0 ; i -- )
18 {
19
20 Console.Write( " {0}/ " , arrInt32[i - 1 ]);
21
22 }
2 for ( int x = 0 ; x < 9 ; x ++ )
3 {
4
5 for ( int y = 0 ; y < 9 - 1 ; y ++ )
6 {
7 if (arrInt32[y] > arrInt32[y + 1 ])
8 {
9 arrInt32[y] ^= arrInt32[y + 1 ];
10 arrInt32[y + 1 ] ^= arrInt32[y];
11 arrInt32[y] ^= arrInt32[y + 1 ];
12 }
13
14 }
15
16 }
17 for ( int i = 9 ; i > 0 ; i -- )
18 {
19
20 Console.Write( " {0}/ " , arrInt32[i - 1 ]);
21
22 }
上面的代码初看没理解有什么特殊的,
还以为
arrInt32[y + 1] ^= arrInt32[y];
arrInt32[y] ^= arrInt32[y + 1];
是多余的。
后来查了下逻辑异或,找到了答案。
------很佩服这样简单高效代码-----------
x^=y; y^=x; x^=y;
可以实现不用临时空间就交换两个整数x,y
-------------------------------------------
两个数(例如x和y)相同(两者都为真或两者都为假)时,
逻辑异或后即为假(通常用0表示),不同(一方为真,一方为假)时,逻辑异或后即为真(通常用1表示)
x y 逻辑异或
0 0 0
0 1 1
1 0 1
1 1 0
很惭愧