Reverse Array Recursively

Source code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;
void reverse(int *A, int N, int i, int j)
{
// base case
if(i >= j) return;
// swap
int t = A[i];
A[i] = A[j];
A[j] = t;
// recursive
reverse(A, N, ++i, --j);
}
void reverse(int *A, int N)
{
reverse(A, N, 0, N-1);
}
int main() {
// your code goes here
int A[5] = {1, 2, 3, 4, 5};
reverse(A, 5);
for(int i = 0; i < 5; i++) {
cout << A[i] << ",";
}
cout << endl;
return 0;
}
Share Comments