Saturday, 27 May 2017

C++ Program for reversing an array in O(n) Time

Algorithm and its implementation to reverse an array in O(n) time is given below:

ALGORITHM:


step 1:    set j=0
step 2:    set k=n-1 /*n is the total number of elements in array */
step 3:    do While j<k:
step 4:             set: temp=array[j]
step 5:             set: array[j]=array[k]
step 6:             set: array[k]=temp
step 7:             set: j=j+1
step 8:             set: k=k-1    


PROGRAM:

#include <iostream>
using namespace std;

int main() {
  int t;    /*t is the test cases */
  cin>>t;
  for(int i=0;i<t;i++)
  {
       int n;    /*n is the number of elements */
       cin>>n;
       int arr[n];
       for(int j=0;j<n;j++)
       {
            cin>>arr[j];
       }
       int temp;
       int j=0;
       int k=n-1;
       while(j<k)
       {
           temp=arr[j];
           arr[j]=arr[k];
           arr[k]=temp;
           j++;
           k--;
       }
       cout<<"\n\nArray after reversal is: \n\n";
       for(j=0;j<n;j++)
       {
           cout<<arr[j]<<" ";
       }
       cout<<"\n\n";
  }
  return 0;
}


OUTPUT:



EmoticonEmoticon