Reversing an array using recursion in c++
This is a functional recursive code for reversing an array in C++. Recursion is used when we want a function to return a value or perform a repeated task. This type of recursion is commonly used in dynamic programming.
The two-pointers approach is an efficient way to reverse an array by utilizing two indices that start from the opposite ends of the array and move towards the center. This method is simple and works in-place, meaning it requires no extra space apart from the input array.
Consider an array: [1, 2, 3, 4, 5]
.
We use two pointers:
start
pointer, which starts at the beginning of the array.end
pointer, which starts at the end of the array.
The idea is to swap the elements at the start
and end
pointers and then move these pointers towards the center. This process is repeated until the start
pointer is no longer less than the end
pointer.
Initial array:
1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|
⬆ | ⬆ | |||
start | end |
- Swap
arr[start]
andarr[end]
:
5 | 2 | 3 | 4 | 1 |
---|---|---|---|---|
⬆ | ⬆ | |||
start | end |
- Move
start
pointer to the right andend
pointer to the left:
5 | 2 | 3 | 4 | 1 |
---|---|---|---|---|
⬆ | ⬆ | |||
start | end |
- Swap
arr[start]
andarr[end]
:
5 | 4 | 3 | 2 | 1 |
---|---|---|---|---|
⬆ | ⬆ | |||
start | end |
- Move
start
pointer to the right andend
pointer to the left:
5 | 4 | 3 | 2 | 1 |
---|---|---|---|---|
⬆ | ||||
start, end |
- Now,
start
is no longer less thanend
, so the process stops.
Here's a C++ implementation of this approach using recursion:
void reverseArr(int arr[], int start, int end){
if(start < end){
swap(arr[start], arr[end]);
reverseArr(arr, start+1, end-1);
}
else return;
}