In this shot, we will learn how to swap two elements in a
In this algorithm, we use a temporary variable to swap the elements.
The value of the first element (arr[0]
) is stored in temp
.
The value of the second index (arr[2]
) is then assigned to the first index (arr[0]
).
The value of temp
is 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 0
in an temp
variable then assigning the value at the last index to index 0, and finally placing the temp
variable stored value at the last index.
std::swap()
to swap elementsThe 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
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 of arr[0]
and arr[size - 1]
, which effectively swaps the first and last elements of the array arr
.