34
loading...
This website collects cookies to deliver better user experience
Arrays
Data structure.💡 Give yourself at least 15-20 mins to figure out the solution :)
start
and end
, initially pointing to the first element and last element of the array respectively.while start < end:
swap(arr[start], arr[end])
start = start + 1 //move start ahead by one step
end = end - 1 //move end back by one step
💡 If you are wondering why there's <
instead of ≤
? It's because start
will be equal to end
only in the case of odd length arrays and they both will point to the middle element of the array. And it does no good to swap it with itself as the array is already reversed by then.
Think what happens when arr.length = 3
(odd), after one iteration, start
and end
both will point to index=1 and array is already reversed.
Think what happens when arr.length = 4
(even), after two iteration, start(2)
will be greater than end(1)
and array will be reversed.
#include<iostream>
using namespace std;
void reverse(int* arr, int start, int end){
//untill we reach the middle
while(start < end){
//swap arr[start] and arr[end]
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;//move start ahead
end--;//move end back
}
}
//driver code
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
reverse(arr, 0, n-1);
for(auto val: arr){
cout<<val<<"\n";
}
return 0;
}
N
: length of the array34