根据维基百科的定义:
插入排序是迭代算法,逐一获得输入数据,逐步产生有序的输出序列。每步迭代中,算法从输入序列中取出一元素,将之插入有序序列中正确的位置。如此迭代直到全部元素有序。
归并排序进行如下迭代操作:首先将原始序列看成 N 个只包含 1 个元素的有序子序列,然后每次迭代归并两个相邻的有序子序列,直到最后只剩下 1 个有序的序列。
现给定原始序列和由某排序算法产生的中间序列,请你判断该算法究竟是哪种排序算法?
输入格式:
输入在第一行给出正整数 N (≤100);随后一行给出原始序列的 N 个整数;最后一行给出由某排序算法产生的中间序列。这里假设排序的目标序列是升序。数字间以空格分隔。
输出格式:
首先在第 1 行中输出Insertion Sort
表示插入排序、或Merge Sort
表示归并排序;然后在第 2 行中输出用该排序算法再迭代一轮的结果序列。题目保证每组测试的结果是唯一的。数字间以空格分隔,且行首尾不得有多余空格。
输入样例 1:
10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0
结尾无空行
输出样例 1:
Insertion Sort
1 2 3 5 7 8 9 4 6 0
结尾无空行
输入样例 2:
10
3 1 2 8 7 5 9 4 0 6
1 3 2 8 5 7 4 9 0 6
结尾无空行
输出样例 2:
Merge Sort
1 2 3 8 4 5 7 9 0 6
结尾无空行
#include<iostream>
#pragma warning (disable:4996)
#include <algorithm>
#include <iostream>
using namespace std;
bool judge(int orgin[], int sorted[],int N);//数组不同返回1
int main() {
int N;
int orgin[100], sorted[100];
scanf("%d", &N);
for (int cnt = 0; cnt < N; cnt++) cin >> orgin[cnt];
for (int cnt = 0; cnt < N; cnt++) cin >> sorted[cnt];
int i, j;
for (i = 0; i < N && sorted[i] <= sorted[i + 1]; i++);
for (j = i + 1; j < N && sorted[j] == orgin[j]; j++);
if (j == N) {
cout << "Insertion Sort" << endl;
sort(orgin, orgin + i + 2);
}
else {
cout << "Merge Sort" << endl;
int flag = 1, beishu = 1;
while (flag) {
flag = judge(orgin, sorted, N);
for (int cnt = 0; cnt < N / beishu; cnt++) {
sort(orgin + beishu * cnt, orgin + beishu * (cnt + 1));
}sort(orgin + N / beishu * beishu, orgin + N);
beishu *= 2;
}
}
for (int cnt = 0; cnt < N; cnt++)
printf("%d%s", orgin[cnt], (cnt != N - 1) ? " " : "");
return 0;
}
bool judge(int orgin[], int sorted[], int N) {
int flag = 0;
for (int cnt = 0; cnt < N; cnt++) {
if (orgin[cnt] != sorted[cnt]) flag = 1;
}
return flag;
}
归并循环中若cnt==N/k,是对一整个数组进行排列,但是其实有可能会有剩余下来的,比如说14,在被归并为4数组 的时候,就会导致有两个没有相邻给他归并,那么我们就要单独对他进行归并,又因为防止越界访问,所以我们循环设置成了cnt<N/k,对最后剩下来的那一部分单独运算
注意:sort()中第二个参数是最后一个元素的后一个地址.
注意下,如果有浮点错误的话,应该是第一个找i那里出问题了,那里必须<=,我也不知为什么