1098 Insertion or Heap Sort (25 point(s))

解法一:

#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;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值