Question -
Given an array, you have to reverse that array.
Example -
Input : arr[]={1,2,3,4,5} n=5;
Output : 5 4 3 2 1
Approach -
we swap first number to last number and second to second last and do this until low is less than or equal to high.
Implementation -
//to reverse an array (sorted or unsorted)
#include<iostream>
using namespace std;
void reversearray(int arr[],int n)
{
int start = 0;
int end=n-1;
while(start<=end){
int temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
start++;
end--;
}
}
int main()
{
int n;
cout<<"Enter the no of element : ";cin>>n;
int arr[n];
cout<<"Enter elements : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
reversearray(arr,n);
//print array elements
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
return 0;
}
Time complixity - O(n)
Comments
Post a Comment