题目注意点
- 由于数据较小,在归并排序时可以使用sort函数代替merge函数
- 先判断是不是插入排序,如果不是直接让输入原序列合并排序到目标序列的下一轮
实现
#include <stdio.h>
#include <algorithm>
using namespace std;
int n, input[105], mid[105], input2[105];
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
bool isEqual(int *a, int *b) {
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
void showArray(int *a) {
for (int i = 0; i < n; i++) {
if (i) printf(" ");
printf("%d", a[i]);
}
}
void merge(int *a, int l1, int r1, int l2, int r2) {
int i = l1, j = l2;
int temp[105], index = 0;
while (i <= r1 && j <= r2) {
if (a[i] <= a[j]) {
temp[index++] = a[i++];
} else {
temp[index++] = a[j++];
}
}
while (i <= r1) temp[index++] = a[i++];
while (j <= r2) temp[index++] = a[j++];
for (i = 0; i < index; i++) {
a[l1 + i] = temp[i];
}
}
void mergeSortBreak(int *a) {
int flag = 0;
for (int step = 2; step / 2 <= n; step *= 2) {
for (int i = 0; i < n; i += step) {
int mid = (i + i + step) / 2 - 1;
if (mid + 1 < n) {
merge(a, i, mid, mid + 1, min(i + step - 1, n - 1));
}
}
if (flag) break;
if (isEqual(a, input2)) flag=1;
}
}
int main(){
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &input[i]);
mid[i] = input[i];
}
for (int i = 0; i < n; i++) {
scanf("%d", &input2[i]);
}
int isInsert = 0, i, j;
for (i = 1; i < n; i++) {
int k = -1;
for (j = i; j > 0 && mid[j] < mid[j - 1]; j--) {
swap(&mid[j], &mid[j - 1]);
}
if (isEqual(mid, input2)) {
isInsert = 1;
}
if (isInsert == 1) {
break;
}
}
int flag2 = 0;
if (isInsert) {
printf("Insertion Sort\n");
for (; i < n; i++) {
for (j = i; j > 0 && mid[j] < mid[j - 1]; j--) {
swap(&mid[j], &mid[j - 1]);
flag2 = 1;
}
if (flag2 == 1) break;
}
showArray(mid);
} else {
printf("Merge Sort\n");
mergeSortBreak(input);
showArray(input);
}
printf("\n");
return 0;
}