Monday, December 31, 2012

Which algorithm is efficient for swapping?

Swapping of two numbers/characters can be done by different ways. Generally all people know swapping using a temporary variable. 
In this post i will tell you how to swap two variables in 3 different ways,  and which algorithm is efficient to swap the variables. 

Here all the below examples are shown in C code(executed in linux environment with gcc compiler).

Method 1:
  • Swapping using a temporary variable:
#include<stdio.h>
void swap(int*,int*);

int main()
{
    int a,b;
    printf("enter 2 numbers\n");
    scanf("%d %d",&a,&b);
    printf("before swapping: a=%d b=%d\n",a,b);
    swap(&a,&b);
    printf("After swapping: a=%d b=%d\n",a,b);

    return 0;
}
void swap(int *a ,int *b)
{
    int temp;
    temp=*a;
    *a=*b;
    *b=temp;
}

Method 2:
  • Swapping without using a 3rd variable
void swap(int *a,int *b)
{
    *a = *a + *b;
    *b = *a - *b;
    *a = *a - *b;
}


Method 3:
  • XOR swap
void XORswap(int *a,int *b)
{
    *a = *a ^ *b;
    *b = *a ^ *b;
   *a = *a ^ *b;
}
-->
Which algorithm is efficient for swapping?
SO, which algorithm is efficient for swapping..each algorithm has its own limitations.
  • In the 2nd method if the addition of the two numbers more than the integer limt, then we can get un expected result.
  • XOR swap algorithm is doesn't give right result for the floating point swapping
  • And also XOR swapping algorithm gives you zero as result if you try to perform swapping on the two variables which contains the same address. So you need to check the address before swapping, like
  • But the XOR swap is useful in some low memory systems like microcontrollers
void XORswap(int *a,int *b)
{
      if(a==b)
          return;
    *a = *a ^ *b;
    *b = *a ^ *b;
    *a = *a ^ *b;
}

Finally, swapping using temporary variable is effficient, as todays systems are having more memory.

If you like this article

No comments:

Post a Comment