堆排序(c++实现)

代码及其注释如下:

注:本代码默认堆树以数组vector的形式存储..

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

void heapinsert(vector<int>& p, int index) {//确定index结点在树中应该在的位置
        while (p[index] > p[(index - 1) / 2]) { //儿子比爸爸大 
               swap(p, index, (index - 1) / 2);//换
               index = (index - 1) / 2;//儿子变爸爸
        }
}
void heapify(vector<int>&p,int index,int heapsize ) {//heapify也是一种确定位置的方法
                                                  
        int left = 2 * index + 1;//左儿子
        while (left < heapsize) {
               int largeist;
               if (left + 1 < heapsize) {
                        largeist = p[left] > p[left + 1] ? left : left + 1;
               }
               else {
                       largeist = left;//找出左右儿子谁更大
               }
               largeist =p[largeist] > p[index] ? largeist : index;//挑出来的儿子再与爸爸比一比 
                                                                     
               if (largeist == index) break;//若是最后最大值为当前节点,直接break
               swap(p,largeist,index);
               index = largeist;
               left = index * 2 + 1;//继续调整堆结构
        }
}
void heapsort(vector<int>& p) {
        if (p.empty()||p.size()==1) {
               return;
        }
        /**
        for (int i =p.size()-1; i>=0; i--) {
               heapify(p, i, p.size());
        }
        **/
        for (int i = 0; i < p.size(); i++) {
               heapinsert(p, i);//让堆变成大根堆
        }
        int n =p.size();
        swap(p,0,--n);//p[0]就是最大的,把它换到它应该去的位置
        while (n > 0) {
               heapify(p, 0, n);//用heapify调整堆后根结点就是当前最大的值。
               swap(p, 0, --n);
        }
}

int main() {
	vector<int>p = {1,2,3,4,5,4,8,5,9,10};
	heapsort(p);
	for (auto i : p) {
		cout << i<<" ";
	}
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值