解法一:
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1010;
int N;
int start[maxn], target[maxn];
void adjust(int low, int high, int A[]){
int i=low, j=i*2;
while(j<=high){
if(j+1<=high&&A[j]<A[j+1])j++;
if(A[j]>A[i]){
swap(A[i], A[j]);
i=j;
j=j*2;
}else break;
}
}
void showArray(int A[]){
for(int i=1; i<=N; i++){
printf("%d", A[i]);
if(i!=N)printf(" ");
}
}
int main(){
scanf("%d", &N);
for(int i=1; i<=N; i++){
scanf("%d", &start[i]);
}
for(int i=1; i<=N; i++){
scanf("%d", &target[i]);
}
int p=2;
while(p<=N&&target[p]>=target[p-1])p++;
int index=p;
while(p<=N&&start[p]==target[p])p++;
if(p==N+1){
printf("Insertion Sort\n");
sort(target+1, target+1+index);
showArray(target);
}else{
printf("Heap Sort\n");
p=N;
while(p>=1&&target[p]>target[p-1])p--;
swap(target[1], target[p]);
adjust(1, p-1,target);
showArray(target);
}
return 0;
}
解法二:
#include<cstdio>
#include<algorithm>
const int maxn=1010;
using namespace std;
int start[maxn], target[maxn], temp[maxn];
int N;
bool isSame(int a[], int b[]){
for(int i=1; i<=N; i++){
if(a[i]!=b[i])return false;
}
return true;
}
void showArray(int a[]){
for(int i=1; i<=N; i++){
printf("%d", a[i]);
if(i!=N)printf(" ");
}
}
bool insert(){
bool flag=false;
for(int i=2; i<=N; i++){
if(i>2&&isSame(temp, target)){
flag=true;
}
sort(temp, temp+i+1);
if(flag){
return true;
}
}
return false;
}
void downAdjust(int low, int high){
int i=low, j=i*2;
while(j<=high){
if(j+1<=high&&temp[j]<temp[j+1])j++;
if(temp[j]>temp[i]){
swap(temp[j], temp[i]);
i=j;
j=j*2;
}else break;
}
}
void heapSort(){
bool flag=false;
for(int i=N/2; i>=1; i--){
downAdjust(i, N);
}
for(int i=N; i>1; i--){
if(i!=N&&isSame(temp, target)){
flag=true;
}
swap(temp[i], temp[1]);
downAdjust(1, i-1);
if(flag){
showArray(temp);
return;
}
}
}
int main(){
scanf("%d", &N);
for(int i=1; i<=N; i++){
scanf("%d", &start[i]);
temp[i]=start[i];
}
for(int j=1; j<=N; j++){
scanf("%d", &target[j]);
}
if(insert()){
printf("Insertion Sort\n");
showArray(temp);
}else{
for(int i=1; i<=N; i++)temp[i]=start[i];
printf("Heap Sort\n");
heapSort();
}
return 0;
}