-
Notifications
You must be signed in to change notification settings - Fork 0
/
swapsections.c
98 lines (84 loc) · 1.97 KB
/
swapsections.c
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <stdio.h>
static int g_swapcount = 0;
void _swap(int* left, int* right)
{
int temp = *left;
*left = *right;
*right = temp;
++g_swapcount;
}
void _reverse(int* datas, int start, int end)
{
int i = start;
int j = end - 1;
while (i < j) {
_swap(&datas[i], &datas[j]);
++i;
--j;
}
}
void reverseswap(int* datas, int sep, int len)
{
_reverse(datas, 0, sep);
_reverse(datas, sep, len);
_reverse(datas, 0, len);
}
void _successiveswap(int* datas, int start, int end, int sep)
{
int frontlen = sep - start;
int backlen = end - sep;
int i = 0;
if (frontlen <= 0 || backlen <= 0) {
return;
}
for (i = 0; i < backlen && i < frontlen; ++i) {
_swap(&datas[i + start], &datas[i + sep]);
}
if (frontlen > backlen) {
_successiveswap(datas, start + backlen, end, sep);
} else {
_successiveswap(datas, sep, end, sep + frontlen);
}
}
void successiveswap(int* datas, int sep, int len)
{
_successiveswap(datas, 0, len, sep);
}
void modswap(int* datas, int sep, int len)
{
int temp = datas[0];
int i = sep;
int pre = 0;
int next = i % len;
while (next != 0) {
datas[pre] = datas[next];
++g_swapcount;
i += sep;
pre = next;
next = i % len;
}
datas[pre] = temp;
++g_swapcount;
}
int main()
{
int i = 0;
int datas[] = { 89, 3, 6, 2, 4, 7, 8, 23, 4, 34 };
int results[] = { 23, 4, 34, 89, 3, 6, 2, 4, 7, 8 };
int len = sizeof(datas) / sizeof(int);
int sep = 7;
//reverseswap(datas, sep, len);
//successiveswap(datas, sep, len);
modswap(datas, sep, len);
printf("Swap-count: %d\n", g_swapcount);
for (i = 0; i < len; ++i) {
if (datas[i] != results[i]) {
printf("error: (datas[%d]=%d) != (results[%d]=%d)\n", i, datas[i], i, results[i]);
break;
}
}
if (i == len) {
printf("Succeed!\n");
}
return 0;
}