SCAU 数据结构 8644 堆排序

Description
用函数实现堆排序,并输出每趟排序的结果

输入格式
第一行:键盘输入待排序关键的个数n
第二行:输入n个待排序关键字,用空格分隔数据

输出格式
第一行:初始建堆后的结果
其后各行输出交换堆顶元素并调整堆的结果,数据之间用一个空格分隔

输入样例
10
5 4 8 0 9 3 2 6 7 1

输出样例
9 7 8 6 4 3 2 5 0 1
8 7 3 6 4 1 2 5 0 9
7 6 3 5 4 1 2 0 8 9
6 5 3 0 4 1 2 7 8 9
5 4 3 0 2 1 6 7 8 9
4 2 3 0 1 5 6 7 8 9
3 2 1 0 4 5 6 7 8 9
2 0 1 3 4 5 6 7 8 9
1 0 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9

#include <iostream>
#include <malloc.h>

using namespace std;

void print_array(int a[],int n)
{
    for(int i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}

void swap(int &a,int &b)
{
    int tmp;
    tmp=a;
    a=b;
    b=tmp;
}

//维护堆的性质
void heapify(int a[],int n,int i)
{
    int largest=i;
    int ilchild=i*2+1;
    int irchild=i*2+2;
    if(ilchild<n&&a[ilchild]>a[largest])
        largest=ilchild;
    if(irchild<n&&a[irchild]>a[largest])
        largest=irchild;
    if(largest!=i) //如果a[i]不是最大值
    {
        swap(a[i],a[largest]); //才要和最小值进行交换
        heapify(a,n,largest); //交换后要维护largest节点大顶堆的性质
    }
}

//利用大顶堆进行排序
void heap_sort(int a[],int n)
{
    int i;
    //建大顶堆
    //要维护原始堆每一个父节点的性质,0也是父节点
    for(i=n/2-1;i>=0;i--)
    {
        heapify(a,n,i);
    }
    print_array(a,n);

    //排序
    //对后n-1个数进行排序,只需要排序n-1趟,即i>0
    for(i=n-1;i>0;i--)
    {
        swap(a[i],a[0]);
        heapify(a,i,0); //维护前i个节点大顶堆的性质
        print_array(a,n);
    }

}

int main()
{
    int n;
    cin>>n;
    int *a=(int*)malloc(sizeof(int)*n);
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
    }
    heap_sort(a,n);
    return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值