这道题乙级也有,突然想用C来做一下
题目有不严谨的地方,比如
10
3 1 2 8 7 5 9 4 6 0
1 2 3 5 7 8 9 4 6 0
这个测试,插入排序,但是9不确定是否排过
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<math.h>
#pragma warning(disable:4996)
using namespace std;
void merge(int* &a, int low, int high,int tt)//low,low+tt-1 low+tt,high两个有序的合并
{
int xx = low;
if (high < low + tt) return;
int *b = (int *)malloc(sizeof(int)*(high - low + 1));
int low2 = low + tt;
int t = 0;
while (low <= xx + tt - 1 && low2 <= high)
{
if (a[low] < a[low2]) b[t++] = a[low++];
else b[t++] = a[low2++];
}
while(low <= xx + tt - 1) b[t++] = a[low++];
while(low2 <= high) b[t++] = a[low2++];
for (int i = 0;i < high - xx + 1;i++)
a[i + xx] = b[i];
}
int main()
{
int N;
int *a, *b;
scanf("%d", &N);
a = (int *)malloc(sizeof(int)*N);
b= (int *)malloc(sizeof(int)*N);
for (int t = 0;t < N;t++)
scanf("%d", a + t);
for (int t = 0;t < N;t++)
scanf("%d", b + t);
int high = N - 1;
while (high >= 0)//从后往前寻找第一个两个数列同一位置值不同的位置
{
if (a[high] == b[high]) high--;
else break;
}
int flag = 0;
for (int t = 1;t <= high;t++)//若此位置前面都有序,则为插入排序
if (b[t] < b[t - 1]) {
flag = 1;break;
}
if (flag) {
printf("Merge Sort\n");
int tem=1;
int t,cnt=1;
flag = 0;
while (flag == 0)//从原始数列开始进行合并排序,每排一次与目标数列对比,如果一样,再排一次进行输出
{
flag = 1;
for (int i = 0;i < N;i++)
if (a[i] != b[i]) {flag = 0;break;}
for (t = 0;t + cnt * 2-1< N;t += cnt * 2)
merge(a, t, t + cnt * 2 - 1, cnt);
merge(a, t, N - 1, cnt);
cnt *= 2;
}
for (int t = 0;t < N;t++)
{
printf("%d", a[t]);
if (t != N - 1) putchar(' ');
}
}
else {
printf("Insertion Sort\n");
while (b[high + 1] > b[high]) high++;//题目不严谨的地方
for (;high >= 0;high--)//继续插排的下一步
if (b[high + 1]<b[high]) {
int tem = b[high];
b[high] = b[high + 1];
b[high + 1] = tem;
}
else break;
for (int t = 0;t < N;t++)//输出
{
printf("%d", b[t]);
if (t != N - 1) putchar(' ');
}
}
putchar('\n');
}