-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03_ReverseArray.cpp
More file actions
80 lines (68 loc) · 1.21 KB
/
03_ReverseArray.cpp
File metadata and controls
80 lines (68 loc) · 1.21 KB
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Reverse Array
#include <iostream>
#include <bits/stdc++.h>
#include <vector>
using namespace std;
// Store the element while progressing and reassign while returning.
// However, using global var ain't recommended.
int i = 0;
void reverseArr(vector<int> &A)
{
if (i == A.size())
{
i = 0;
return;
}
int temp = A[i];
++i;
reverseArr(A);
A[i] = temp;
++i;
}
// swap using two pointer
void reverseArr(vector<int> &A, int r, int l = 0)
{
if (l >= r)
{
return;
}
swap(A[l], A[r]);
reverseArr(A, r - 1, l + 1);
}
// Swap using one pointer
void reverse(vector<int> &A, int i=0) {
if (i >= A.size()/2) {
return ;
}
swap(A[i], A[A.size()-i-1]);
reverse(A, i+1);
}
int main()
{
vector<int> v = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int a : v)
{
cout << a << " ";
}
cout << endl;
// Reverse the array
reverseArr(v);
for (int a : v)
{
cout << a << " ";
}
cout << endl;
reverseArr(v, v.size() - 1);
for (int a : v)
{
cout << a << " ";
}
cout << endl;
reverse(v);
for (int a : v)
{
cout << a << " ";
}
cout << endl;
return 0;
}