Swap two elements of 1D array in C++
In this tutorial, we will learn how to swap two elements in a one-dimensional array. This we will see through either using a manual swap function or a built-in swap function in C++. Hope you will like this tutorial. Let’s get started.
Swap two elements of a 1D array in C++
To swap two elements in a 1D array we can do it in two ways. First, we will do it manually, and second, we will do using the built-in C++ function that swap() method.
Suppose we are given a 1D array such as an array having size 6 and we want to swap two elements having values 1 and 3 so that the array becomes sorted in decreasing order.
array[6] = {5,4,1,2,3,0}
After swap we will have array[6] = {5,4,3,2,1,0}.
Steps to Swap two elements.
- First, create a temporary variable such as temp and store the value of that particular index.
- Then, the value of the second index in the first index.
- Lastly, store the temp value in the second index.
Let’s understand with example code. Then it will be very clear.
#include <iostream>
using namespace std;
void printArr (int arr[], int length) {
for(int i = 0; i < length; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
// declare array
const int length = 5;
int arr[length] = {5, 2, 3, 4, 1};
// temp variable in swapping
int temp;
cout << "Original array: ";
printArr(arr, length);
// swapping second and fourth element
temp = arr[1];
arr[1] = arr[3];
arr[3] = temp;
cout << "Array with second and fourth element swapped and sorted: ";
printArr(arr, length);
return 0;
}OUTPUT: Original array: 5 2 3 4 1 Array with second and fourth element swapped and sorted: 5 4 3 2 1
Now we will see using the built-in swap() function in C++. This function helps in swapping two elements without using a third variable such as the temp variable as we used in the above case.
Syntax :
void swap(int var1, int var2)
#include <iostream>
using namespace std;
void printArr (int arr[], int size) {
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
const int size = 5;
int arr[size] = {5, 2, 3, 4, 1};
cout << "Original array: ";
printArr(arr, size);
swap(arr[1], arr[3]); // built-in swap() method
cout << "Array with second and fourth element swapped: ";
printArr(arr, size);
return 0;
}
OUTPUT:
Original array: 5 2 3 4 1
Array with second and fourth element swapped: 5 4 3 2 1
Hope you liked this tutorial. Keep Learning !!!!
Also Read: C++ Null Pointers with examples
Leave a Reply