Reverse an array
Tue Nov 12 2024 18:19:54 GMT+0000 (Coordinated Universal Time)
Saved by
@Pavan_05
[#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
//i gave an array as reference and two pointers for left right index of array, set a base condition that is left index is greater than right then return else swap value at left and right and I am using this funtion recirsively ustil the base condition meets by increasing and decreasing left and right index
void reverserecursive(vector<int>&arr, int l, int r){
while(l>=r) {
return;
}
swap(arr[l],arr[r]);
reverserecursive(arr, l+1, r-1);
}
//here i just iterated first half and swapped with corresponding elements from the end.
void reverseusingswap(vector<int>&arr){
int n = arr.size();
for(int x=0; x<n/2; x++){
swap(arr[x],arr[n-x-1]);
}
}
//here i took two pointers for left and right index and used swap to swap the left and right index value by increasing and decreasing the index elements
void reversetwopointer(vector<int>&arr, int l, int r){
while(l<=r){
swap(arr[l], arr[r]);
l++;
r--;
}
}
// here I used an inbuilt method reverse and reversed the elements for this algorithm header should be added
void reverseinbuiltmethod(vector<int>&arr){
reverse(arr.begin(), arr.end());
}
int main() {
vector<int>arr = {1,2,3,4,5};
reverseinbuiltmethod(arr);
for(int i = 0; i< arr.size(); i++){
cout<<arr[i];
}
return 0;
}]
content_copyCOPY
Comments