• Register
search
Log In

Methods of reversing an array in C++ are

  • reverse() method

  • In-place implementation

  • Using recursion

 

reverse() method

 

C++ provides a header file algorithm.h which contains function reverse(). This helps in reversing the elements of an array. This is the simplest way of doing this.

#include <iostream>
#include <algorithm>
using namespace std;

// Utility function to print contents of an array
void print(int arr[], int n)
{
	for (int i = 0; i < n; i++) {
		cout << arr[i] << " ";
	}
}

// Utility function to reverse elements of an array
void reverse(int arr[], int n)
{
	reverse(arr, arr + n);
}

int main()
{
	int arr[] = { 1, 2, 3, 4, 5 };
	int n = sizeof(arr)/sizeof(arr[0]);

	reverse(arr, n);
	print(arr, n);

	return 0;
}

 

In-place implementation

 

This method is more logical. In the previous method all the work was done by the function reverse() but in this method we have to write more code to make it work. 

In this method we are going to read the elements from both ends of the array and swap them. 

#include <iostream>
#include <algorithm>
using namespace std;

// Utility function to print contents of an array
void print(int arr[], int n)
{
	for (int i = 0; i < n; i++) {
		cout << arr[i] << " ";
	}
}

// Utility function to reverse elements of an array
void reverse(int arr[], int n)
{
	for (int low = 0, high = n - 1; low < high; low++, high--) {
		swap(arr[low], arr[high]);
	}
}

int main()
{
	int arr[] = { 1, 2, 3, 4, 5 };
	int n = sizeof(arr)/sizeof(arr[0]);

	reverse(arr, n);
	print(arr, n);

	return 0;
}

 

Using recursion

 

You can also use recursion. The logic behind the recursion is the same as the in-place implementation.

#include <iostream>
#include <algorithm>
using namespace std;

// Utility function to print contents of an array
void print(int arr[], int n)
{
	for (int i = 0; i < n; i++) {
		cout << arr[i] << " ";
	}
}

// Recursive function to reverse elements of a sub-array formed
// by arr[low, high]
void reverse(int arr[], int low, int high)
{
	if (low < high)
	{
		swap(arr[low], arr[high]);
		reverse(arr, low + 1, high - 1);
	}
}

int main()
{
	int arr[] = { 1, 2, 3, 4, 5 };
	int n = sizeof(arr)/sizeof(arr[0]);

	reverse(arr, 0, n-1);
	print(arr, n);

	return 0;
}

 

posted May 27 in c++ 100 points