void reverse_in_place(string& s){
int last = s.length() -1;
for (int i = 0; i <= last/2; i++){
char temp = s[i]; //i is initially 0
s[i] = s[last-1]; //swapping first and last character
s[last- i] = temp;
}
}
This is a c++ program.
convert the same function for array and vectors.
//The required function for vectors:
void reverse_in_place_vector( vector <int> &v){
//passing vector to function
int last = v.size() - 1;
for (int i=0; i <= last ; i++ )
{
int temp = v[i]; // i is
initially zero
v[i] = v[last]; //
swapping first and last character
v[last] = temp;
last--;
}
}
//The required function for arrays:
void reverse_in_place_array( int a[] , int n){ // passing array
and its size n to function
int last = n - 1;
for (int i=0; i <= last ; i++ )
{
int temp = a[i];
a[i] = a[last];
a[last] = temp;
last--;
}
}
Please refer to the screenshot of the code to understand the indentation of the code:
Hope this helped. Please do upvote and if there are any queries please ask in the comments section.
Get Answers For Free
Most questions answered within 1 hours.