A1098 Insertion or Heap Sort (25 分)堆排序

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=110;
int n;
int origin[maxn], temp[maxn], changed[maxn];
bool issame(int a[], int b[])
{
	for (int i = 0; i < n; i++)
	{
		if (a[i] != b[i]) return false;
	}
	return true;
}
void show(int temp[])
{
	for (int i = 1; i <= n; i++)
	{
		printf("%d", temp[i]);
		if (i != n) printf(" ");
	}
}
bool insert()
{
	bool flag = false;
	for (int i = 2; i <= n; i++)
	{
		if (i != 2 && issame(temp, changed)) flag = true;
		sort(temp, temp + i + 1);
		if (flag == true) 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 + 1] > temp[j]) j = j + 1;
		if (temp[j] > temp[i])
		{
			swap(temp[j], temp[i]);
			i = j;
			j = 2 * i;
		}
		else break;
	}
}
void heap()
{
	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, changed)) flag = true;
		swap(temp[1], temp[i]);
		downadjust(1, i - 1);
		if (flag == true)
		{
			show(temp);
			return;
		}
	}
}
int main()
{
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &origin[i]);
		temp[i] = origin[i];
	}
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &changed[i]);
	}
	if (insert() == true)
	{
		printf("Insertion Sort\n");
		show(temp);
	}
	else
	{
		printf("Heap Sort\n");
		for (int i = 1; i <= n; i++)
		{
			temp[i] = origin[i];
		}
		heap();
	}
	return 0;
}

看网上叫柳婼大神的解法:(平均运行时间比前面多了2ms左右,但是省了很多行代码)

#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;

void downadjust(vector<int> &a,int low,int high)
{
	int i = low;
	int j = 2 * i;
	while (j <= high)
	{
		if (j + 1 <= high && a[j + 1] > a[j]) j = j + 1;
		if (a[j] > a[i])
		{
			swap(a[j], a[i]);
			i = j;
			j = 2 * i;
		}
		else break;
	}
}
int main()
{
	int n;
	scanf("%d", &n);
	vector<int> a(n+1), b(n+1);
	for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
	for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
	int p = 2;
	while (p<=n&&b[p - 1] <= b[p]) p++;
	int index = p;
	while (p<=n&&a[p] == b[p]) p++;
	if (p == n + 1)
	{
		printf("Insertion Sort\n");
		sort(b.begin() + 1, b.begin() + index + 1);
	}
	else
	{
		printf("Heap Sort\n");
		p = n;
		while (b[1] < b[p]) p--;
		swap(b[1], b[p]);
		downadjust(b,1, p-1);
	}
	printf("%d", b[1]);
	for (int i = 2; i <= n; i++)
		printf(" %d", b[i]);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值