-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotate.cpp
More file actions
51 lines (41 loc) · 897 Bytes
/
rotate.cpp
File metadata and controls
51 lines (41 loc) · 897 Bytes
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
#include <iostream>
using namespace std;
/**
Rotate array using array indexes
*/
void rotate(int a[], unsigned size, int shift)
{
int copy[size];
for (int i = 0; i < size; i++) {
copy[i] = a[i];
}
for (int i = 0; i < size; i++) {
a[i] = copy[(i + shift) % size];
}
}
/**
Rotate array using pointers
*/
void rotate_p(int a[], unsigned size, int shift)
{
int copy[size];
int * a_p = a;
int * copy_p = copy;
for (copy_p = copy; copy_p < copy + size; copy_p++) {
* copy_p = * a_p;
a_p++;
}
copy_p = copy;
for (a_p = a; a_p < a + size; a_p++) {
* a_p = * (copy_p + ((a_p - a) + shift) % size);
}
}
int main() {
int a[] = {1, 2, 3, 4, 5};
rotate_p(a, 5, 2);
for (int i = 0; i < 5; i++) {
cout << a[i] << ' ';
}
cout << '\n';
return 0;
}