Tricky Algorithm -Implementation Swap function Code in c++

Differnt Swap Algorithm

    -Swap Classic

    -Swap without Temporay

   -Swap using Bitwise

 You can use this snippet to implement tricky Swap Algorithm

//****************************************
// Author : Sanjay Vyas
// Purpose : To Implement Differnt Swap Alogorithm

//****************************************
#include <iostream.h>

// Swap Classsic Using Temp Variable
void Swap_Classic(int &ValFirst,int & ValSecond)
{
 int ValTemp;
 ValTemp =ValFirst;
 ValFirst= ValSecond;
 ValSecond = ValTemp;
}
// Swap New Without Using Temp Variable
void Swap_New(int &ValFirst,int & ValSecond)

 ValFirst = ValFirst + ValSecond ;
 ValSecond= ValFirst – ValSecond ;
 ValFirst = ValFirst – ValSecond ;
}
// Swap New using bitwise
void Swap_Bitwise(int &ValFirst,int & ValSecond)

 ValFirst= ValFirst ^ ValSecond ; //  1080 = 1000 ^ 2000
 ValSecond=ValFirst ^ ValSecond ; // 1000 = 1080 ^ 2000
 ValFirst= ValFirst ^ ValSecond ; // 2000 = 1080 ^ 1000
}
void Reset_Value(int &ValFirst,int & ValSecond)
{
 ValFirst = 1000;
 ValSecond= 2000;
}
int main()
{
 int ValueFirst=1000;
 int ValueSecond=2000;
 cout << “Implemented Different Swap Function” << endl;
 cout << “Original Value:” << endl;
 cout << ” First :” << ValueFirst << endl;
 cout << ” Second:” << ValueSecond << endl;
 
 Swap_Classic (ValueFirst,ValueSecond);
 cout << “Swap Classsic:” << endl;
 cout << ” First :” << ValueFirst << endl;
 cout << ” Second:” << ValueSecond << endl;

 Reset_Value(ValueFirst,ValueSecond);

 Swap_New(ValueFirst,ValueSecond); 
 cout << “Swap New:” << endl;
 cout << ” First :” << ValueFirst << endl;
 cout << ” Second:” << ValueSecond << endl;

 Reset_Value(ValueFirst,ValueSecond);

 Swap_Bitwise(ValueFirst,ValueSecond); 
 cout << “Swap New:” << endl;
 cout << ” First :” << ValueFirst << endl;
 cout << ” Second:” << ValueSecond << endl;
 
 cout << “<- End ->” << endl;
}

One Response to “Tricky Algorithm -Implementation Swap function Code in c++”

  1. csabill Says:

    The “swap” thing is generic for different prog. languages. The classic implementation of the two would use the +=, -= & ^= operators. Not the elaborate forms.

    I.e.

    lhs ^= rhs;
    rhs ^= lhs;
    lhs ^= rhs;


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: