How to swap the position of two array elements in C++

Swapping elements in an array is handy in many standard algorithms like bubble sort. In this article, we shall look at the basic principles of swapping and swapping positions in an array and implement them in C++ program.

Swapping two array elements

Swapping basically means interchanging the values of two variables. This is usually done by storing one variable in a dummy variable and then assigning it the value of the other. Then the dummy variable can be used to change the other variable.

The following C++ code illustrates the concepts:

#include <iostream>
int main()
{
  int x{}; 
  int y{};  // x and y are the test variables
  std::cout << "Enter two values:";
  std::cin >> x >> y;
  int k; //dummy variable
  k = x;
  x = y;
  y = k;
  std::cout << "The values after swapping are:" << x <<" "<< y << "\n";
}

Output:

Enter two values:4 5
The values after swapping are:5 4

Swapping elements in an array

An array is a collection of elements of the same datatype allocated in contiguous memory. The index operator is used to access each element. Thus, the two index values can be considered as a variable, and swapping principles can be applied.

The following code illustrates the point:

#include <iostream>
int main()
{
  int a[5];
  std::cout << "Enter the 5 five numbers: ";
  for (int i = 0; i < 5; i++)
  {
    std::cin >> a[i];
  }
  int i, j; //positions to be swapped
  std::cout << "Enter the positions to be swapped: "; std::cin >> i >> j;
  int dummy;//dummy variable;
  dummy = a[i];
  a[i] = a[j];
  a[j] = dummy;
  std::cout << "Elements after swapping are: ";
  for (int x : a)
  {
    std::cout << x << " ";
  }
  std::cout << std::endl;
}

Output:
Enter the 5 five numbers: 5 4 3 2 1
Enter the positions to be swapped: 1 2
Elements after swapping are: 5 3 4 2 1

A better approach

The STL of C++ provides a function template called std::swap which can be used to swap elements without much verbose.

The syntax for the function is:

std::swap<T>(Val1 ,Val 2)

Where val1 and val2 are the elements to be swapped. T is the datatype of Val 1 and val2. Both values should be of the same type.

The following code illustrates the use of std::swap to swap array elements:

#include <iostream>
int main()
{
  int a[5];
  std::cout << "Enter the 5 five numbers: ";
  for (int i = 0; i < 5; i++)
  {
    std::cin >> a[i];
  }
  int i, j; //positions to be swapped
  std::cout << "Enter the positions to be swapped: "; std::cin >> i >> j;
  std::swap(a[i], a[j]); //simple compared to the other process
  std::cout << "Elements after swapping are: ";
  for (int x : a)
  {
    std::cout << x << " ";
  }
  std::cout << std::endl;
}

The output is the same as the above code.

Although the principle behind swapping elements was illustrated in this article, it should be seldom used. Always resort to std::swap whenever possible.

Leave a Reply

Your email address will not be published. Required fields are marked *