How to swap two elements in 1D array in C++
In this shot, we will learn how to swap two elements in a
Code
Example 1: Manually swapping elements
In this algorithm, we use a temporary variable to swap the elements.
-
The value of the first element (
arr[0]) is stored intemp. -
The value of the second index (
arr[2]) is then assigned to the first index (arr[0]). -
The value of
tempis then assigned to the second index (arr[2]).
#include <iostream>using namespace std;// user defined function to print arrayvoid printArr (int arr[], int size) {for(int i = 0; i < size; i++) {cout << arr[i] << " ";}cout << endl;}int main() {// declare arrayconst int size = 5;int arr[size] = {5, 2, 3, 4, 1};// temp variable to aid in swappingint temp;cout << "Original array: ";printArr(arr, size);// swapping first and last elementtemp = arr[0];arr[0] = arr[size - 1];arr[size - 1] = temp;cout << "Array with first and last element swapped: ";printArr(arr, size);return 0;}
Lines 5-10: We defined a function with the name of
printArr(), which will iterate over the array and print all its indexes.Line 16: We defined an array with the name of
arr[]and and size of 5.Lines 25-27: We swapped the first and last values of the array by temporarily storing the value at index
0in antempvariable then assigning the value at the last index to index 0, and finally placing thetempvariable stored value at the last index.
Example 2: Using std::swap() to swap elements
The built-in swap() function can swap two values in an array.
template <class T> void swap (T& a, T& b);
The swap() function takes two arguments of any
Return value
This function returns nothing.
#include <iostream>using namespace std;// user defined ftn to print arrayvoid printArr (int arr[], int size) {for(int i = 0; i < size; i++) {cout << arr[i] << " ";}cout << endl;}int main() {// declare arrayconst int size = 5;int arr[size] = {5, 2, 3, 4, 1};// temp variable to aid in swappingint temp;cout << "Original array: ";printArr(arr, size);// swapping first and last elementswap(arr[0], arr[size - 1]);cout << "Array with first and last element swapped: ";printArr(arr, size);return 0;}
Lines 5-10:We defined the
printArr()in a similar way we used in the previous example.Line 25: We used the built-in
swap()function provided by the C++ standard library. We're using it to swap the values ofarr[0]andarr[size - 1], which effectively swaps the first and last elements of the arrayarr.