Data Structures and Algorithms
In this tutorial we will learn to reverse elements of an Array data structure.
In order to reverse the elements of an array we take help of temp
variable and then swap the first element with the last element, second element with the second last element, till we reach the middle.
Before: 1 2 3 4 5 ^ ^ Pass 1: 5 2 3 4 1 ^ ^ Pass 2: 5 4 3 2 1
So, if there are n elements in the array then will iterate n/2 time.
Time complexity is O(n).
In the following C++ example we are going to reverse an array of size 5.
#include <iostream>
using namespace std;
const int SIZE = 5;
int arr[SIZE];
int END = -1;
void freshInsertElements()
{
cout << "REFRESH!" << endl;
cout << "Inserting " << SIZE << " elements in the array arr..." << endl;
int i;
for (i = 0; i < SIZE; i++)
{
arr[i] = i + 1;
}
END = SIZE - 1;
}
void print()
{
cout << "Printing the content of array arr..." << endl;
int i;
for (i = 0; i <= END; i++)
{
cout << "arr[" << i << "] = " << arr[i] << endl;
}
cout << endl;
}
void reverse()
{
int temp, i;
for (i = 0; i < END / 2; i++)
{
temp = arr[i];
arr[i] = arr[END - i];
arr[END - i] = temp;
}
}
int main(void)
{
freshInsertElements();
print();
reverse();
print();
return 0;
}
Output
REFRESH!
Inserting 5 elements in the array arr...
Printing the content of array arr...
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Printing the content of array arr...
arr[0] = 5
arr[1] = 4
arr[2] = 3
arr[3] = 2
arr[4] = 1
ADVERTISEMENT