Home »
Data Structure »
Array Data Structure
Write a program to reverse an array
C++ implementation to reverse an array using multiple approaches.
Submitted by Vikneshwar GK, on March 04, 2022
Consider an integer array, of size n. The task at hand is to reverse the given array.
Example:
Input:
array[]= {1, 2, 3, 4, 5}
Output:
array[] = {5, 4, 3, 2, 1}
Input:
array[]= {10, 9, 8, 7, 6}
Output:
array[] = {6, 7, 8, 9, 10}
Solution 1: Using Pointers
This method involves using two pointers, start, and end, to point two ends of the array. Then we swap the elements at start and end and perform start++ and end-- as long as start is less than end.
C++ Implementation:
#include <iostream>
#include <unordered_set>
using namespace std;
// Function to rearrange the array
void rearrangeArray(int array[], int length)
{
int start = 0, end = length - 1;
while (start < end) {
int temp = array[start];
array[start] = array[end];
array[end] = temp;
start++;
end--;
}
}
// Function to print the array
void printArray(int array[], int length)
{
for (int i = 0; i < length; i++) {
cout << array[i] << " ";
}
}
// Main function
int main()
{
int array[100], N, element;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++) {
cout << "Enter element " << i + 1 << ": ";
cin >> array[i];
}
rearrangeArray(array, N);
printArray(array, N);
return 0;
}
Output:
Enter Number of elements: 6
Enter element 1: 1
Enter element 2: 2
Enter element 3: 3
Enter element 4: 4
Enter element 5: 5
Enter element 6: 6
6 5 4 3 2 1
Time Complexity: O(n), where n is the length of the array.
Solution 2: Using Recursive Function
This solution uses the same concept as the previous solution except the implementation is done using recursion.
C++ Implementation:
#include <iostream>
#include <unordered_set>
using namespace std;
// Function to rearrange the array
void rearrangeArray(int array[], int start, int end)
{
if (start >= end)
return;
int temp = array[start];
array[start] = array[end];
array[end] = temp;
// Recursive Function calling
rearrangeArray(array, start + 1, end - 1);
}
// Function to print the array
void printArray(int array[], int length)
{
for (int i = 0; i < length; i++) {
cout << array[i] << " ";
}
}
// Main function
int main()
{
int array[100], N, element;
cout << "Enter Number of elements: ";
cin >> N;
for (int i = 0; i < N; i++) {
cout << "Enter element " << i + 1 << ": ";
cin >> array[i];
}
rearrangeArray(array, 0, N - 1);
printArray(array, N);
return 0;
}
Output:
Enter Number of elements: 6
Enter element 1: 2
Enter element 2: 3
Enter element 3: 4
Enter element 4: 5
Enter element 5: 7
Enter element 6: 8
8 7 5 4 3 2
Time Complexity: O(n), where n is the length of the array.