PTA Insertion or Heap Sort 思路分析及代码解析

一、前导信息

1. 需要掌握的知识

插入排序、堆排序

2. 题目信息

  1. 题目来源:PTA
  2. 题目地址:Insertion or Heap Sort

二、解题思路分析

  1. Insert or Merge的同类题:根据N趟排序后的元素序列(N是未知的)推断出使用的排序算法,随后打印N+1趟排序后的元素序列
  2. 和Insert or Merge的不同点,题目中使用的排序算法是插入排序和堆排序,只要正确实现插入排序和堆排序,基本就可以AC。其他注意事项请参考 Insert or Merge,在此不再赘述
  3. 堆排序和归并排序的代码实现,自己需要加强

三、AC代码

#include <iostream>
using namespace std;
#define max 10000

typedef int ElementType;
ElementType a[max], b[max], a_bak[max];

bool insert_sort(ElementType a[], int n);
void heap_sort(ElementType a[], int n);
void DownFilter(ElementType r[], int root, int n);
bool compare(ElementType a[], ElementType b[], int n);
void Print(ElementType a[], int n);

int main()
{
	int n;
	cin >> n;

	for (int i = 0; i < n; i++)
		cin >> a[i];

	for (int i = 0; i < n; i++)
		a_bak[i] = a[i];

	for (int i = 0; i < n; i++)
		cin >> b[i];

	if (insert_sort(a, n));
	else
		heap_sort(a_bak, n);

	return 0;
}

bool insert_sort(ElementType a[], int n) 
{
	int P, i, tmp;
	bool flag = false;

	for (P = 1; P < n; P++)
	{
		tmp = a[P]; 

		for (i = P; i > 0 && (a[i-1] > tmp); i--)
			a[i] = a[i - 1];  

		a[i] = tmp;

		if (flag)
		{
			Print(a, n);
			return true;
		}

		if (compare(a, b, n))
		{
			cout << "Insertion Sort" << endl;
			flag = true;
		}
	}

	return false;
}

void Print(ElementType a[], int n)
{
	int i = 0;
	cout << a[i++];

	for (; i < n; i++)
		cout << " " << a[i];

	return;
}

bool compare(ElementType a[], ElementType b[], int n)
{
	bool flag = true;
	int count = 0;

	while (flag && count < n)
	{
		if (a[count] != b[count])
			flag = false;
		count++;
	}
	return flag;
}

void DownFilter(ElementType r[],int root, int n) // root mean root Node 
{
	int Parent, Child, x;

	x = r[root]; //gain the root's value

	for (Parent = root; (Parent * 2 + 1) < n; Parent = Child)
	{
		Child = Parent * 2 + 1;

		if ((Child != n - 1) && (r[Child] < r[Child + 1]))
			Child++;

		if (x > r[Child])
			break;
		else
			r[Parent] = r[Child];
	}

	r[Parent] = x;

	return;
}

void heap_sort(ElementType r[], int n)
{
	int i, tmp;
	bool flag = false;

	for (i = (n / 2 - 1); i >= 0; i--) //Creat MaxHeap through DownFilter Func. 'n/2 - 1'代表最右的那棵子树
		DownFilter(r,i, n); // 'n/2 - 1'代表最右的那棵子树,调整顺序也就是从最后一棵子树开始,从右向左逐渐调整

	for (i = n - 1; i > 0; i--)
	{
		//Swap(A[0], A[i]);
		//cout << "Yes,this is Heap Sort's for Func." << endl;
		tmp = r[0];
		r[0] = r[i];
		r[i] = tmp;

		DownFilter(r,0,i);
		//Print(r, n); cout << endl;

		if (flag)
		{
			Print(r, n);
			return;
		}

		if (compare(r, b, n))
		{
			cout << "Heap Sort" << endl;
			flag = true;
		}

	}
}

四、参考资料

  1. 浙江大学 陈越、何钦铭老师主讲的数据结构
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值