Search code examples
cselection-sort

Why Swapping without third variable not working here?


I was writing the c language code for selection sort. It was working fine If the swapping was done with using Third Variable but when I changed the method of swapping without using third variable as shown in the code comment below. It is showing wrong Output( zeros at some positions).I cannot figure out why this is happening?

I have tried to swap two numbers without third variable in another program for the same type of conditions. But it is working fine there. But Why not in my selection sort program.

#include<stdio.h>
void selectsort(int * ,int);//selection sort function


int main(){
int a[5];
int i,n=5;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
selectsort(a,n);
printf("Sorted Array is:\n");

for(i=0;i<5;i++)
printf("%d\n",a[i]);
}



/* Below is selection sort function definition*/
void selectsort(int*p ,int q){
int i,j,h,temp;
for(i=0;i<q-1;i++){
h=i;
for(j=i+1;j<q;j++){
if(p[h]>p[j]){
h=j;
}
}

/* below code is to swap the two numbers ( p[i] and p[h]) without 
  using third variable , but it is NOT WORKING here
  (giving wrong output) BUT WORKING IF THIRD VARIABLE IS USED.Why?*/
p[i]=p[i]+p[h];
p[h]=p[i]-p[h];
p[i]=p[i]-p[h];
}
}

Solution

  • Your values of h and i are not quaranteed to be different. Swapping in this case will not only not swap anything but also mess up your memory.

    void selectsort(int*p ,int q){
      int i,j,h,temp;
      for(i=0;i<q-1;i++){
        h=i;   // <=== Here you start with identical values
        for(j=i+1;j<q;j++){
          if(p[h]>p[j]){
            h=j;    // This may or may not be executed.
          }
        }
    
        // Here h can still be at same value as i.
        // What happens in this case is shown in the comments below:
        p[i]=p[i]+p[h];  // p[i]=p[i]+p[i];  ==> p[i] *=2; 
        p[h]=p[i]-p[h];  // p[i]=p[i]-p[i];  ==> p[i] = 0;
        p[i]=p[i]-p[h];  // p[i]=p[i]-p[h];  ==> p[i] = 0;
      }
    }
    

    You could add something like this before doing the swapping:

        if (i==h)
          continue;
    

    Note:

    Apart from academic cases I would not suggest using such an approach. Swapping without a temporary variable has lots of downsides:

    • Only works for integer types
    • Needs handling for overflow etc.
    • Needs handling for identical storage locations.
    • Needs extra arithmetic operations causing more code and longer execution time
    • Is confusing readers and harder to maintain

    It also only has one advantage

    • Saves stack storage for 1 variable.

    If your goal is to confuse readers, then you should search for a version using XOR instead of arithmetics. ;)