Quick actions

cmd+k|ctrl+k

Navigation

Languages

reversing the array in c++

Snippet info

Language

Cpp

Visibility

public

Author

umashankar

Created

2021-04-29T08:45:41.570932Z

Updated

2021-04-29T08:51:46.673359Z

/*
    An In-place algorithm is an algorithm that does not need an extra space 
    and produces an output in the same memory that contains the data by 
    transforming the input ‘in-place’. However, a small constant extra space
    used for variables is allowed.
    
    In-place means that the algorithm does not use extra space for manipulating
    the input but may require a small though nonconstant extra space for its
    operation. Usually, this space is O(log n), though sometimes anything in o(n)
    (Smaller than linear) is allowed

    Reversing an array in-place and not in-place 
*/
/*1st method (not in-place)*/
#include <iostream>
#include <array>
using namespace std;

void reverse_nip(int* arr,int n);
void reverse_ip(int* arr,int n);

int main() {
    int arr[5] = {11,22,13,4,1};
    int n = sizeof(arr)/sizeof(arr[0]);
    reverse_nip(arr,n);
    cout << "After reversing the array is: \n";
    for(int i=0; i<n; ++i){
        cout << arr[i] << "\t";
    }
    return 0;
}

void reverse_nip(int* arr, int n){
    int rev[n];
    for(int i=0; i<n; ++i){
        rev[i] = arr[n-i-1];
    }
    for(int i=0; i<n; ++i){
        arr[i] = rev[i];
    }
    return;
}

void reverse_ip(int* arr, int n){
    for(int i=0; i<n/2; ++i){
        swap(arr[i],arr[n-i-1]);
    }
    return;
}
INFO