堆排序

#include <iostream>


using namespace std;


void MAX_HEAPIFY(int *&A,int i,int maxlength);
void BUILD_MAX_HEAP(int *&A,int maxlength);
void HEAPSORT(int *A,int heap_size,int maxlength);




int main()
{
    int maxlength;
    int *data;
    cout<<"输入你想要排序的数组的长度:"<<endl;
    cin>>maxlength;
    data=new int[maxlength];
    cout<<"依次输入你的数组:"<<endl;
    for(int i=0;i<maxlength;i++)
        cin>>data[i];
    BUILD_MAX_HEAP(data,maxlength);
    HEAPSORT(data,maxlength,maxlength);
}


void MAX_HEAPIFY(int *&A,int i,int maxlength){
    int leftchild;
    int rightchild;
    int largest;
    leftchild=i*2;
    rightchild=leftchild+1;
    if(leftchild<=maxlength&&A[leftchild-1]>A[i-1])
        largest=leftchild;
    else
        largest=i;
    if(rightchild<=maxlength&&A[rightchild-1]>A[largest-1])
        largest=rightchild;
    if(largest!=i){
        int exchange=A[i-1];
        A[i-1]=A[largest-1];
        A[largest-1]=exchange;
        if(largest<maxlength/2)
            MAX_HEAPIFY(A,largest,maxlength);
        //这里也是判断largest是不是叶子节点,这样的话可以减小工作量。
    }
}


void BUILD_MAX_HEAP(int *&A,int maxlength){
    int x=maxlength/2;
    //这里不需要对叶子节点进行排序,只需要对根节点进行排序,可以减小工作量。
    for(int i=x;i>=1;i--)
        MAX_HEAPIFY(A,i,maxlength);
}


void HEAPSORT(int *A,int heap_size,int maxlength){
    for(int i=maxlength;i>=1;i--){
        cout<<A[0]<<"  ";
        int exchange;
        exchange=A[0];
        A[0]=A[heap_size-1];
        A[heap_size-1]=exchange;
        heap_size=heap_size-1;
        MAX_HEAPIFY(A,1,heap_size);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值