一、前导信息
1. 需要掌握的知识
插入排序、堆排序
2. 题目信息
- 题目来源:PTA
- 题目地址:Insertion or Heap Sort
二、解题思路分析
- Insert or Merge的同类题:根据N趟排序后的元素序列(N是未知的)推断出使用的排序算法,随后打印N+1趟排序后的元素序列
- 和Insert or Merge的不同点,题目中使用的排序算法是插入排序和堆排序,只要正确实现插入排序和堆排序,基本就可以AC。其他注意事项请参考 Insert or Merge,在此不再赘述
- 堆排序和归并排序的代码实现,自己需要加强
三、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;
}
}
}