大小堆的建立



#include<iostream>
#include<cstdlib>
#include<vector>
#include<cassert>
using namespace std;
template<class T>
struct Less
{
bool operator()(T& l,T& r)
{
return l<r;
}
};
template<class T>
struct Great
{
bool operator()(T& l,T& r)
{
return l>r;
}


};
template<class T,template<class> class Compare>
class Heap
{
public:
Heap(const T* a,size_t size)
{
int i=0;
_a.reserve(size);
for(i=0;i<size;i++)
{
_a.push_back(a[i]);
}
for(i=(size-2)/2;i>=0;i--)
{
AdjustDown(i);          //默认大堆建立
}
Display();
}
size_t Size()
{
return _a.size();
}


bool Empyt()
{
return _a.size()==0;
}
void Insert(T& t)
{
_a.push_back(t); 
size_t size=_a.size();
AdjustUp(size-1);
Display();


}
void Delete()
{
size_t size=_a.size();  
        assert(size>0);  
swap(_a[0];_a[size-1]);
_a.pop_back();
AdjustDown(0);
Display();
}
void Display()
{
if(_a.size()!=0)
{
  for(int i=0;i<_a.size();i++)
  {
  cout<<_a[i]<<" ";
  
  }
}
cout<<endl;
}
void Sort()
{
_Sort(_a.size()-1);
Display();

}
protected:
void AdjustDown(size_t parent)            //向下调整算法建立大堆
{
size_t child =parent*2+1;  
        while(child<_a.size())  
        {  
            Compare<T> com;  
        if(child+1<_a.size()&&com(_a[child+1],_a[child]))  
        {  
            ++child;  
        }  
            if(com(_a[child],_a[parent]))  
            {  
            swap(_a[parent],_a[child]);  
            parent=child;  
            child=parent*2+1;  
        }  
        else  
            break;  
}
}
void AdjustUp(size_t child)              //向上调整算法建立小堆
{
assert(!child>_a.size);
Compare<T> com; ;
int parent=(child-1)/2;
while(child>0)
{
if(com(_a[child],_a[parent]))
{
swap(_a[child],_a[parent]);
child=parent;
parent=(child-1)/2;
}
else
break;
}
}
void _Sort(size_t child)
{
int parent=(child-1)/2;
while(child>0)
{
if(_a[child]<_a[parent])
{
swap(_a[child],_a[parent]);
   child=parent;
}
if(_a[child-1]<_a[child])
{
swap(_a[child-1],_a[child]);
}
else 
break;
}

}
private:
vector<T> _a;


};
int main()
{
int a[]= {10,11, 13, 12, 16, 18, 15, 17, 14, 19};
Heap<int,Less> heap(a,sizeof(a)/sizeof(a[0]));
system("pause");
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值