DS内排—堆排序

本文详细介绍了一种高效的排序算法——堆排序,并提供了完整的C++实现代码。通过实例讲解了如何构建小顶堆并进行数据的降序排序,适合初学者理解和掌握堆排序的基本原理和操作步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值