DS内排—堆排序
题目描述
给定一组数据,使用堆排序完成数据的降序排序。(建小顶堆)。
输入
数据个数n,n个整数数据
输出
初始创建的小顶堆序列
每趟交换、筛选后的数据序列,输出格式见样例
样例输入
8 34 23 677 2 1 453 3 7
样例输出
8 1 2 3 7 23 453 677 34
8 2 7 3 34 23 453 677 1
8 3 7 453 34 23 677 2 1
8 7 23 453 34 677 3 2 1
8 23 34 453 677 7 3 2 1
8 34 677 453 23 7 3 2 1
8 453 677 34 23 7 3 2 1
8 677 453 34 23 7 3 2 1
#include <iostream>
using namespace std;
class heapSort{
int *array;
int len;
public:
heapSort(int n);
~heapSort();
void Sift(int pos,int length);
void Sort();
void outPut();
};
heapSort::heapSort(int n) {
len=n;
array = new int[n];
for(int i=0;i<n;i++)
cin>>array[i];
for(int i=n/2;i>=0;i--)
Sift(i,len);
//输出堆初始化
outPut();
}
heapSort::~heapSort() {
delete []array;
}
void heapSort::Sift(int pos, int length) {
int lChild=2*pos+1,rChild=2*pos+2;
if(lChild<length) //左孩子不超过最大值
{
if(rChild<length) //存在右孩子
{
if(array[lChild]<array[rChild])
{
if(array[lChild]<array[pos])
{
int temp=array[pos];
array[pos]=array[lChild];
array[lChild]=temp;
Sift(lChild,length); //和左孩子交换之后,筛选左孩子
}
}
else{
if(array[rChild]<array[pos])
{
int temp=array[pos];
array[pos]=array[rChild];
array[rChild]=temp;
Sift(rChild,length); //和右孩子交换之后,筛选右孩子
}
}
}
else //只有左孩子,没右孩子
{
if(array[lChild]<array[pos])
{
int temp=array[pos];
array[pos]=array[lChild];
array[lChild]=temp;
Sift(lChild,length); //和左孩子交换之后,筛选左孩子
}
}
}
}
void heapSort::Sort() {
for(int i=len-1;i>0;i--) //从最后一个结点开始筛选,每次减一
{
int temp=array[i];
array[i]=array[0];
array[0]=temp;
Sift(0,i);
outPut();
}
}
void heapSort::outPut() {
cout<<len<<' ';
for(int i=0;i<len;i++) {
cout << array[i];
if(i!=len-1)
cout<<' ';
}
cout<<endl;
}
int main()
{
int n;
cin>>n;
heapSort myHeap(n);
myHeap.Sort();
return 0;
}