-
Notifications
You must be signed in to change notification settings - Fork 0
/
1089.cpp
121 lines (105 loc) · 2.03 KB
/
1089.cpp
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100 + 5;
bool isSame(int a[], int b[], int len);
bool insertSort(int temp[], int target[], int len);
bool mergeSort(int temp[], int target[], int len);
int main()
{
int origin[maxn];
int temp[maxn];
int target[maxn];
int n;
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &origin[i]);
temp[i] = origin[i];
}
for (int i = 0; i < n; i++)
{
scanf("%d", &target[i]);
}
if (insertSort(temp, target, n))
{
printf("Insertion Sort\n");
for (int i = 0; i < n; i++)
{
printf("%d", temp[i]);
if (i < n - 1)
printf(" ");
}
}
else
{
// 恢复 temp 序列
for (int i = 0; i < n; i++)
{
temp[i] = origin[i];
}
mergeSort(temp, target, n);
printf("Merge Sort\n");
for (int i = 0; i < n; i++)
{
printf("%d", temp[i]);
if (i < n - 1)
printf(" ");
}
}
return 0;
}
// 判断数组a和b是否相同
bool isSame(int a[], int b[], int len)
{
for (int i = 0; i < len; i++)
{
if (a[i] != b[i])
return false;
}
return true;
}
bool insertSort(int temp[],int target[], int len)
{
bool flag = false; // 记录是否存在排序的中间步骤与target数组相同
for (int i = 1; i < len; i++)
{
if (i != 1 && isSame(temp, target, len)) // 中间步骤与目标序列相同,且不是初始序列
{
flag = true;
}
// 以下为插入部分
int t = temp[i];
int j = i;
while (j > 0 && temp[j - 1] > t)
{
temp[j] = temp[j - 1];
j--;
}
temp[j] = t;
if (flag == true)
return true; // 说明找到了目标序列
}
return false; // 没有找到目标序列
}
bool mergeSort(int temp[], int target[], int len)
{
bool flag = false;
for (int step = 2; step / 2 < len; step *= 2)
{
if (step != 2 && isSame(temp, target, len))
{
flag = true; // 中间步骤与目标序列相同,且不是初始序列
}
for (int i = 0; i < len; i += step)
{
sort(temp + i, temp + min(i + step, len));
}
if (flag == true)
{
return true;
}
}
return false;
}