这两个函数用于在使用函数执行选择排序时使用指针交换变量selectionSort(int *,int).但是在排序之后,数组的一些元素变为零.
void selectionSort(int *x,int len){
int i,j,max;
for(i=len-1;i>=0;i--){
max = 0;
for(j=1;j<=i;j++){
if(x[j]>x[max]){
max = j;
}
}
swap(x+max,x+i);
}
}
void swap(int *a,int *b){
//This one works perfectly
int temp;
temp=*b;
*b=*a;
*a=temp;
}
void swap(int *a,int *b){
//This one gives unexpected results
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
Run Code Online (Sandbox Code Playgroud)
使用算术运算符交换两个整数会导致整数溢出.最好坚持传统的方法.
顺便说一句,您可以使用旧学校的按位XOR运算符进行交换(用于交换寄存器中的值),但它不会比使用临时变量的方法带来任何好处.这些天编译器足够聪明,可以优化代码.
if (*a == *b) // If both integers are same then do not perform swap operation
return;
*a ^= *b;
*b ^= *a;
*a ^= *b;
Run Code Online (Sandbox Code Playgroud)