swap c++ code example

Example 1: what is time complexity of swap function

The Behaviour is Equivalent to: 

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}

Syntax : Swap(a,b) // a = Number 1 , b = Number 2

Time Complexity: It makes one constructions and one assignments
				 So, Linear O(n) time.

Example 2: swap in cpp

int a{}, b{}, temp{};
cin >> a >> b;

  //===================== METHOD-1
   temp = a;
   a = b;
   b = temp;

  //===================== METHOD-2 ( XOR ^ )
  // example: a^b =  5^7
   a = a ^ b;   // 5^7
   b = a ^ b;   // 5 ^ 7 ^ 7  //5 ( 7 & 7 dismissed)
   a = a ^ b;   // 5 ^ 7 ^ 5  //7 ( 5 & 5 dismissed)

  //===================== METHOD-3  ( swap() )
  swap(a, b);

  cout << "a " << a << endl;
  cout << "b " << b << endl;

Example 3: what did swap method return in c++

Return Value: The function does not return anything, it swaps the values of the two variables

Example 4: c++ swap function

int main()
{
	int a = 5;
	int b = 10;
  
	swap(a, b);
  
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
}

Tags:

Cpp Example