算法思路:
1 三个数组,分别存放原始数据,最终修改后的数据,以及从最初到最终的不断变化的数据。
2.对这个temp数组,一次次判断通过插入排序后的状态是不是等于了最终数组。如果等于了,说明这就是使用的插入排序。
3.否则就是使用的排序。对其一次次的调整,观察其是否等于了最终数组。到一定时候停下来,做完下一步调整之后,输出。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <stdio.h>
#include <math.h>
#include <queue>
#include <vector>
#include <cstring>
#include <cmath>
using namespace std;
const int n=111;
int origin[n],temp[n],changed[n];
int num;
bool isSame(int a[],int b[]){
for(int i=1;i<=num;i++){
if(a[i]!=b[i])
{return false;}
}
return true;
}
bool insertsort(){
bool flag=false;
int i;
for(i=2;i<=num;i++){
if(i!=2&&isSame(changed,temp)){
flag=true;
}
sort(temp,temp+i+1);
if(flag==true){
return true;
}
}
return flag;
}
void printarry(int a[]){
for(int i=1;i<=num;i++){
printf("%d",a[i]);
if(i<num){
printf(" ");
}else{
printf("\n");
}
}
}
void downadjust(int low,int high){
int i=low;
int j=2*i;
while(j<=high){
if(j+1<=high&&temp[j]<temp[j+1]){//这里j+1<=high不能忽略,否则导致很多测试集不可以通过。
j++;
}
if(temp[i]<temp[j]){
swap(temp[i],temp[j]);
i=j;
j=2*i;
}else{
break;
}
}
}
void heapsort(){
bool flag=false;
for(int i=num/2;i>=1;i--){
downadjust(i,num);
}
for(int i=num;i>=1;i--){
if(i!=num&&isSame(temp,changed)){
flag=true;
}
swap(temp[1],temp[i]);
downadjust(1,i-1);
if(flag==true){
printarry(temp);
return;
}
}
}
int main()
{
scanf("%d",&num);
for(int i=1;i<=num;i++){
scanf("%d",&origin[i]);
temp[i]=origin[i];
}
for(int i=1;i<=num;i++){
scanf("%d",&changed[i]);
}
if(insertsort()){
printf("Insertion Sort\n");
printarry(temp);
}else{
printf("Heap Sort\n");
for(int i=1;i<=num;i++){
temp[i]=origin[i];
}
heapsort();
}
}