Write a program to reverse an array

Write a program to Reverse an Array?

Array is the sequential collection of similar elements. Array is a fixed size data structure. Arrays can be accessed by index which starts from zero. Reversing the array helps in arranging the all the elements of an array like we are reading elements from the end. We have to write a C++ program to reverse the given array.

Reverse Array

There are various methods to reverse an array.

INPUT: 1 2 3 4 5

OUTPUT: 5 4 3 2 1

Method1

TIME COMPLEXITY: O(N)

SPACE COMPLEXITY: O(1)

We take two variables start (point at first element of an array) and end (Point at last element of an array).

Algorithm

1. Loop till start is less than end.

2. Keep on swapping the elements pointed by start and end.

3. Increment start and Decrement end variable.

4. As start equals end or Greater than end then we will stop the loop.

 

Program for Method 1:

#include <bits/stdc++.h>
using namespace std;

int main()
{
	int arr[] = {4,1,8,9,11,3,77,2};
	int N = sizeof(arr)/sizeof(arr[0]);			
	
	int start =0 , end = N-1;
	
	while(start < end)
	{
		swap(arr[start++],arr[end--]);
	}
		
	for(int i=0;i<N;i++)
	{
		cout<<arr[i]<<" ";
	}
	
	cout<<endl;		
}

Method 2

TIME COMPLEXITY: O(N)

SPACE COMPLEXITY: O(N)

Algorithm

Like Method1, we will do traversing forward and backward by swapping values. But in this case we will use recursion. It uses extra space because of the usage of Stack.

Program for Method 2:

#include <bits/stdc++.h>
using namespace std;

void reverse(int arr[],int N,int start,int end)
{
	if(start > end)
	{
		return ;
	}	
	else
	{
		swap(arr[start],arr[end]);
		reverse(arr,N,start+1,end-1);
	}
}

int main()
{
	int arr[] = {4,1,8,9,11,3,77,2};
	int N = sizeof(arr)/sizeof(arr[0]);		
	reverse(arr,N,0,N-1);	

	for(int i=0;i<N;i++)
	{
		cout<<arr[i]<<" ";
	}
}
Try It

 


Method 3

TIME COMPLEXITY: O(N)

SPACE COMPLEXITY: O(1)

Algorithm

1. Take the input in vector variable .

2. Use STL function reverse(variable.begin(),variable.end())                                                                  

Program for Method 3:

#include <bits/stdc++.h>
using namespace std;

int main()
{
	int arr[] = {4,1,8,9,11,3,77,2};
	int N = sizeof(arr)/sizeof(arr[0]);
	vector V;
			
	for(int i=0;i<N;i++)
	{
		V.push_back(arr[i]);	
	}
		
	reverse(V.begin(),V.end());
		
	for(int i=0;i<N;i++)
	{
		cout<<V[i]<<" ";
	}		
	
	cout<<endl;
}
Try It

 


Next > < Prev
Scroll to Top