heap_sort-----C++

本文介绍了一种使用C++实现的堆排序算法。该算法通过构建最大堆的方式进行排序,并提供了详细的代码实现。从构建初始堆到调整堆结构,直至完成整个排序过程。

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

/*************************************************************************
	> File Name: heap_sort.cpp
	> Author: ryq
	> Email: ranyongqing@163.com 
	> Created Time: 2014年05月23日 星期五 11时02分19秒
 ************************************************************************/

#include<iostream>
#include<vector>
using namespace std;

template<typename T>
void build_heap_partion(vector<T> &a,int i,int len)
{
    int lpos = 2*i+1;
    int rpos = 2*i+2;
    int tmp = 0;
    int j = i;
    while(j < len && lpos < len){
        if(rpos != len && a[lpos] < a[rpos])
            tmp = rpos;
        else
            tmp = lpos;
        if(a[tmp] > a[j]){
            T k = a[tmp];
            a[tmp] = a[j];
            a[j] = k;
        }
        else
            break;
        j = tmp;
        lpos = 2*j+1;
        rpos = 2*j+2;
    }
}

template<typename T>
void build_heap(vector<T> &des)
{
    int size = des.size();
    for(int i = size/2; i >= 0; i--){
        build_heap_partion(des,i,size);
    }
}

template<typename T>
void heap_sort(vector<T> &des)
{
    for(int i = des.size()-1 ; i > 0; i--){
        int tmp = des[i];
        des[i] = des[0];
        des[0] = tmp;
        build_heap_partion(des,0,i);
    }
        
}



int main()
{
    int a[] = {81,94,11,96,12,35,17,95,28,58,41,75,15};
    vector<int> des(a,a+sizeof(a)/sizeof(int));
    build_heap(des);
    heap_sort(des);
    for(vector<int>::iterator it = des.begin(); it != des.end(); it++)
        cout<<*it<<" ";
    cout<<endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值